LOOPS IN PYTHON
Now that we have learned about the conditions in python, it’s time to focus on loops in python where we will execute a block of code number of times. Python programming language provides repetition of a specific block of code multiple times
Why Loop at all?
The main reason why we need looping in programs is to make complex problems simpler as sometimes we won’t be writing the whole program to go through each query if the functionality is same. For example, if we want to print the numbers from 1 to 10, we could use iterations inside a loop; in that way we can only write the code once and repeat the functionality as much as we want through looping.
The main advantages of using loops in python is that it saves your time, you don’t have to write the same code every time to perform the same functionality; also loops make your code look clean.
Types of Loop
A while loop in python continues to execute the code as long as the given condition is true, if it becomes false, then the loop stops.
Another reason to use while loop is when we aren’t sure about how many times to iterate.
Syntax of While Loop
while expression: statements
In the above syntax, a while loop starts by checking the expression, if the expression is true, the loop continues to statements. After making an iteration, it goes back to expression and continues to execute through the statements until the expression becomes False.
Print n as long as n is less than 10:
n = 1 while n < 10: print(n) n += 1
In the above example, the variable n is already set to 1, and a while loop is set to a condition where n is less than 10, then on line 3 the print statement prints n where currently 1 is stored, on line 4 the n is incremented by 1 and becomes 2 and n now holds 2. The loop continues to execute and increment until n becomes 10; when n becomes 10 the expression becomes false, hence the loop stops.
Note: The while loop will run infinite times if ‘n’ doesn’t get an increment, hence it will make your program unstoppable and may cause errors.
While Loops with Else:
Python allows us to use else statement with the while loop, let’s suppose that if the while expression turns out to be False then we may use an ‘else’ statement to indicate the user that the program will no longer run further.
n = 1 while n < 10: print(n) n += 1 else: print("The program has ended since n is greater than 10")
1 2 3 4 5 6 7 8 9 The program has ended since n is greater than 10
For loop is a python loop which repeats a group of statements for a given number of times. It is always a good practice to use the for loop when we know the number of iterations.
Syntax of For Loop
for variable in sequence: statement 1 statement 2 ...
Here is an example of a list containing fruits, let us use for loop to go through each known number of fruit:
fruits = ['apple','grapes', 'oranges', 'bananas'] for fruit in fruits: print(fruit)
When you will run the program, the result will be:
apple grapes oranges bananas
Using the range() function in for Loop
We can use the range() function using for loops and in that range we can define the number of times we want to iterate; for example if we want to print natural numbers up to 10 then we have to define a range of 11, since the range() function starts at index 0.
#print natural numbers upto 10 for n in range(11): print(n)
0 1 2 3 4 5 6 7 8 9 10
You can use the for loop to print each letter of a string as well, for example:
#print python tricks each character for character in 'python tricks': print(character)
p y t h o n t r i c k s
Using the if-else statements with For Loop:
Python language supports the usage of if-else statements with for loop. If-else statements comes handy if you want to execute the loop with an applied condition, as long as the condition is met the loop continues to execute; else the loop gets terminated.
#Checking which toppings are available using if-else with for loop icecream_toppings = ['chocolate', 'strawberry', 'blueberry', 'cotton candy', 'cherry'] available_toppings = ['chocolate','blueberry'] for toppings in icecream_toppings: if toppings in available_toppings: print("Available toppings are: " + toppings) else: print("Sorry we don't have " + toppings) print("finished making your icecream")
At first we define a list of total icecream_toppings in this example. Next we made a list of available_toppings that are currently present. Now if we find anything that is not available currently like ‘strawberry’ , ‘cotton candy’ and ‘cherry’ then we loop through the list of available_toppings. Inside the loop we check to see if the available_toppings is present in the list of icecream_toppings, if it is then we add the available toppings on the ice cream. If the available_toppings is not in the list of icecream_toppings, the else block will run. The else block will tell which toppings are not currently in stock.
Available toppings are: chocolate Sorry we don't have strawberry Available toppings are: blueberry Sorry we don't have cotton candy Sorry we don't have cherry finished making your icecream
Python supports using the nested loop that is a loop within a loop. The following example is an explanation of how a nested loop works.
Syntax of Nested Loops:
A nested loop of for loop looks like this:
for variable in sequence: for variable in sequence: statement 1 statement 2
A nested loop for while loop looks like this:
while expression: while expression: statement 1 statement 2
Let’s look at an example of a nested loop containing for loops inside it:
#Printing tables of 1 to 10 using nested loops for i in range(1,11): for j in range(1,11): print(i*j) print("\n")