In this python loop tutorial you will learn how to write different type of loops in python, like any other object oriented programming language, in python we have different type of loop structure, here you learn all python loop syntax with examples.
Loop is basically a repetitive process of doing same thing based on some predefine conditions, that means some piece of code will be executed again and again.
Like other programming languages, there are different types of loop in python.
In this example below you can see how to loop through string array variable using for loop
def getCountries(self): countries = ["India", "USA", "UK", "Canada", "UAE"]; for c in countries: print(c)
This is an example of looping through a string and printing each character.
def getLetters(self): string = "this is a for loop example"; for c in string: print(c)
This is how you can use break in for loop, we want to exit the loop when our if condition is satisfied
countries = ["India", "USA", "UK", "Canada", "Australia"]; for c in countries: print(c) if c == "UK": break
Using continue statement we can stop looping the current iteration, and continue to move next. continue statement can be very useful when you have multiple statement or function to be executed in each loop, for any specific condition we can skip to next, without executing any other function inside .
countries = ["India", "USA", "UK", "Canada", "Australia"]; for c in countries: print(c) if c == "UK": continue
While loop in python is very similar to if statement, we also can use while with else statement, like the way we write if and else, we can also write while and else.
While (condition): Keep working
count = 0 while (count <= 4): count = count + 1 print("count value :", count)
We also can use else statement with while loop, like when condition is satisfied if there is any function to be executed.
count = 0 while (count <= 4): count = count + 1 print("count value :", count) else : print("i have to enter now")
Look at above code, using else statement like the way we write if else.
countries = ["India", "USA", "UK", "Canada"]; types = ["Good", "Very Good", "Not Good"]; for c in countries: for t in types: print(c, t)
In python we can loop through any range, here is an example of using range function
for c in range(4): print(c)
There are different overloads in range function,
range(start, stop, step=optional)
for c in range(2,8,2): print(c)
In python coding, indentation is very important, how much space you keep before next line start, will decide the code block. So while writing python loop, make sure you give right space in next statement.