Data Science with Python Certification Traini ...
- 94k Enrolled Learners
- Live Class
Dealing with redundant code and repetitive commands can be a nightmare for any programmer. Python makes use of loops, control and conditional statements to overcome this hurdle. This article will help you understand loops in python and all the terminologies that surround loops.
If you want to master the concepts of loops in Python by Certified Python Expert, you can check out the below video where these topics are covered on a broader gauge
This Edureka “Python Loops” tutorial will help you in understanding different types of loops used in Python. You will be learning how to implement all the loops in python practically.
Loops in Python allow us to execute a group of statements several times. Lets take an example to understand why loops are used in python.
Suppose, you are a software developer and you are required to provide a software module for all the employees in your office. So, you must print the details of the payroll of each employee separately. Printing the details of all the employees will be a tiresome task, instead you can use the logic for calculating the details and keep on iterating the same logic statement. This will save your time and make your code efficient.
The illustration below is the flowchart for a loop:
The execution starts and checks if the condition is True or False. A condition could be any logic that we want to test in our program. If its true it will execute the body of the loop and if its false, It will exit the loop.
Conditional statements in Python support the usual logical conditions from mathematics.
These statements can be used in several ways, most commonly in if statement.
Let us understand the concept of if statements.
An if statement is written using the ‘if’ keyword, The syntax is the keyword ‘if’ followed with the condition.
Below is the flowchart of the if statement:
As you can see, the execution encounters the if condition and acts accordingly. If it is true, it executes the body and if it is false, it exits the if statement.
a = 10 b = 20 if a < b : print(" b is greater")
Above code snippet illustrates the basic example of how a condition is used in the if statement.
When it reaches the if statement it checks whether the value of b is greater or not. If b is greater, it prints “b is greater“. Now if the condition is false, it exits the if statement and executes the next statement. In order to print the next statement, we can add a keyword ‘else’ for the alternate result that we wish to execute. Lets move to the else statement for better understanding.
The else keyword catches anything that is not caught by the preceding conditions. When the condition is false for the if statement, the execution will move to the else statement.
Lets take a look at the flowchart of else statement below:
As you can see, when the if statement was false the execution moved to the body of else. Lets understand this with an example.
a = 10 b = 20 if a < b : print(" b is greater") else: print(" a is greater")
The first condition is not true, so we will move to the next statement which is the else statement and print “b is greater”.
In case we have more conditions to test, we can also use elif statement.
elif statement in layman term means “try this condition instead”. Rest of the conditions can be used by using the elif keyword.
Let us look at the code below:
a = 10 b = 20 if a < b : print(" b is greater") elif a == b : print(" a is equal to b ") else: print(" a is greater")
Since a != b, “b is greater” will get printed here.
Note: python relies on indentation, other programming languages use curly brackets for loops.
A for loop is used to execute statements, once for each item in the sequence. The sequence could be a list, a Dictionary, a set or a string.
A for loop has two parts, the block where the iteration statement is specified and then there is the body which is executed once every iteration.
Unlike while loop, we already specify the number of times the iterations must execute. for loop syntax takes three fields, a Boolean condition, initial value of the counting variable and the increment of the counting variable.
Look at the example to understand this better:
days = ["sun" , "mon" , "tue" , "wed", "thu", "fri", "sat"] for x in days: print(x)
Here we were iterating through the list. To iterate through a code for a specified number of times we could use the range() function.
Range function requires a specific sequence of numbers. It starts at 0 and then the value increments by 1 until the specified number is reached.
for x in range(3) print(x)
It will print from 0-2, the output will look like
0 1 2
Note: the range (3) does not mean the values from 0-3 but the values from 0-2.
Below is another example using the condition statements:
num = int(input("number")) factorial = 1 if num < 0 : print(" invalid input") elif num == 0: print(" factorial is 1") else: for i in range( 1 , num+1): factorial = factorial * i print(factorial)
The ‘while’ loop executes the set of statements as long as the condition is true.
It consists of a condition block and the body with the set of statements, It will keep on executing the statement until the condition becomes false. There is no guarantee to see how long the loop will keep iterating.
Following is the flowchart for while loop:
To understand this let’s take a look at the example below.
i = 1 while i < 6 : print(i) i += 1
Output: it will print 1 2 3 4 5
The execution will continue until value of i reaches 6.
The while loop requires the relevant variable to be ready, here we need an indexing variable, which could be any value.
Lets consider another example:
num = int(input("enter number")) while num > 0: if num < 13: print("the number is too large") break elif num < 13: print("number too small") break elif num == 13: print("exit: congratulations") break
We might need to control the flow of the execution to favor a few conditions in some cases, so let’s understand the loop control statements in Python.
To control the flow of the loop or to alter the execution based on a few specified conditions we use the loop control statements discussed below. The control statements are used to alter the execution based on the conditions.
In Python we have three control statements:
Break statement is used to terminate the execution of the loop containing it. As soon as the loop comes across a break statement, the loop terminates and the execution transfers to the next statement following the loop.
As you can see the execution moves to the statement below the loop, when the break returns true.
Let us understand this better with an example:
for val in "string" : if val == "i": break print(val) print("the end")
s t r The end
Here the execution will stop as soon as the string “i” is encountered in the string. And then the execution will jump to the next statement.
The continue statement is used to skip the rest of the code in the loop for the current iteration. It does not terminate the loop like the break statement and continues with the remaining iterations.
When continue is encountered it only skips the remaining loop for that iteration only.
for val in "string" : if val == "i": continue print(val) print("the end")
Output: s t r n g the end
It will skip the string “i” in the output and the rest of the iterations will still execute. All letters in the string except “i” will be printed.
The pass statement is a null operation. It basically means that the statement is required syntactically but you do not wish to execute any command or code.
Take a look at the code below:
for val in "please": if val == "a": pass print("pass block") print(val)
p l e pass block a s e
The execution will not be affected and it will just print the pass block once it encounters the “a” string. And the execution will start at “a” and execute the rest of the remaining iterations.
Lets understand how we use a while loop using a break statement with an example below:
i = 1 while i < 6 : print(i) if i == 3 : break i += 1
Output: it will print 1 2
The execution will be terminated when the iteration comes to 3 and the next statement will be executed.
Let’s take an example for continue statement in a while loop:
i = 1 while i < 6: print(i) if i == 3 : continue i += 1
Output: 1 2 4 5
Here the execution will be skipped, and the rest of the iterations will be executed.
Python allows us to use one loop inside another loop, Following are a few examples
An example to use a for loop inside another for loop:
for i in range(1 , 6): for j in range(i): print( i , end="") print()
1 2 2 3 3 3 4 4 4 4
Below is the basic syntax to use a nested while loop:
while expression: while expression: statement(s) statement(s)
An example to show a nested while and for loop:
travelling = input("yes or no") while travelling == "yes" : num = int(input("number of people")) for num in range( 1 , num+1): name = input("name") age = input("age") gender = input("gender") print(name) print(age) print(gender) travelling = input("oops missed someone")
In this program we have used a while loop and inside the body of the while loop, we have incorporated a for loop.
The concepts discussed in this blog will help you understand the loops in Python. This will be very handy when you are looking to master Python and will help you make your code efficient. Python is a widely used high-level language.
Have any queries? do not forget to mention them in the comments and we will get back to you.