Loops
Sometimes while coding programs there is often a need arises to repeat some instructions certain number of times. In such case loops are what you are looking for.
while loop
while loops checks for a condition and if it returns true then it execute the instructions within its block. After execution it again checks for the condition. The loop will continue to execute until and unless the condition becomes false or it is forced to break the loop.
Syntax for using while loop:
while condition: #do something
Keep in mind that condition should be such that it eventually somewhere goes false else you will stuck in an infinite loop.
Example
i=10 while i>0: print(i, end=' ') i = i-1
Output:
10 9 8 7 6 5 4 3 2 1
Here we have defined a variable i having value 10. while condition checks whether the value is greater than 1 or not. If condition goes true, it will execute its block. In this case prints value of i and then decrements it.
for loop
for loop is a lot different in python as compared with any other programming language.
Syntax for using for loop:
for i in sequence: #do this
Here sequence can be a string, a list, a tuple or a dictionary.
Example
list = [1,2,3,4,5] for i in list: print(i, end=' ')
Output:
1 2 3 4 5
range() function
range function is used to create numeric range of values and can come in handy while using for loops.
Syntax for using range():
range(x) or range(x, y)
range function with single numeric parameter 'x' creates range of numeric values between 0 to x(excluding x).
Example
>>> range(10) output: range(0,10)
range function with two paramters 'x' and 'y' creates range of numberic values between x to y(excluding y).
Example
>>> range(10, 20) output: range(10,20)
Now lets see how we can use it with for loop
Example
for i in range(10): print(i, end=' ')
Output:
1 2 3 4 5 6 7 8 9
Nested loops
Loop inside another loop is known as nested loop. You can use a while loop inside a for loop or vice versa. You can also use while inside another while loop or a for inside another for loop.
Example
for i in range(1,4): print('outer loop',i) for j in range(1,4): print('inner loop',j,end=' ') print() print()
Output:
outer loop 1
inner loop 1 inner loop 2 inner loop 3
outer loop 2
inner loop 1 inner loop 2 inner loop 3
outer loop 3
inner loop 1 inner loop 2 inner loop 3