Welcome to another post on our blog and our Python tutorial series, Learn Python with me. Today, in this post, we will discuss Python Control Statements.
Why do we need Control Statements in programming?
We used several programs so far in this tutorial series, and most of those programs are simple programs that the python interpreter executes each line one after the other. This kind of execution is called ‘Sequential Execution’. For example, consider the program below, which adds two numbers.
#program to add two numbers
a1=20
a2=30
result=a1+a2
print("The result is",result)
Output
The result is 50
The program mentioned above is an excellent example for sequential execution as the statements are executed each line one after the other by the Python interpreter. However, you cannot use this concept to build programs that require complex logic. And as a programmer, you might need to write code to repeat a group of statements numerous times. Or you might require to jump directly from one block of code to another. The only way you can achieve all these requirements is by using the control statements in Python. Before discussing the Control statements, we need to discuss the Indentation or the significant white spaces in Python.
Indentation in Python
If you want to learn Python, it is essential to learn Indentation in Python. The Indentation in Python refers to the significant whitespace that is used to highlight the blocks of code. Usually, Python uses four spaces, but you can decrease or increase it in your programs. Let us consider the example below.
Python Control Statements
The statements that we can control or if we can change its execution flow are called control statements. Listed below are the Python control statements.
- if statement
- if..else statement
- if..elif..else statement
- while loop
- for loop
- else suite
- break statement
- continue statement
- pass statement
- assert statement
- return statement
You must note that unlike other programming languages like C and Java, the switch statement is not available in Python. Let us now have a detailed look at each kind of control statement in Python.
“if” statement
The “if statement” in Python depends on whether the mentioned condition is True or False. If the condition is true, then the statement given after colon (:) will be executed. Or else, the statement after the colon (:) will not be executed. Please find below the format of the “if statement”.
if condition:
statements
Let us write a simple example program using the “if statement” to understand it better.
company="i-Sapna"
if(company=="i-Sapna"):
print("The company is i-Sapna")
Output
The company is i-Sapna
“if … else ” statement
The “if-else ” statement is used to add both True and False conditions in your program. If the condition evaluates to be true, the statement block related to True(if) will be executed. If it evaluates to be false, the statement block associated with False(else) will be performed. Please refer to the format below.
if condition:
statement1
else:
statement2
Let us look at an example now.
#program to find if a number is odd or even
a=int(input("Enter a number: "))
if(a%2==0):
print("The number {0} you have entered is even".format(a))
else:
print("The number {0} you have entered is odd".format(a))
Output
Enter a number: 11
The number 11 you have entered is odd
In the program above, we can see that since 11 is not an even number, the condition is evaluated as false as per the logic, and the statement block concerning “else” gets executed, and “The number 11 you have entered is odd” gets printed in the output.
“if … elif … else” statement
The “if … elif … else” statement is used in programs when a programmer requires to test multiple conditions. Please refer to the format below.
if condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
elif condition4:
statement4
else:
statement5
Let us now look at an example.
a=int(input("Enter number from keyboard "))
if a==11:
print("You have entered 11")
elif a==22:
print("You have entered 22")
elif a==33:
print("You have entered 33")
else:
print("You have entered number other than 11, 22, and 33")
Output
Enter number from keyboard 99
You have entered number other than 11, 22, and 33
while loop in Python
The control statements that we have discussed so far follows only a one-way execution. It means that they execute only once and never go back to the beginning of the statement. But by using the loops in Python, we can run a set of statements any number of times based on logic.
Using the “while loop” in Python, you can execute a set of statements any number of times depending on the True or False of the condition or logic. The execution comes out of the loop only when the condition is false. As long as the condition is true, the while loop will execute its same statements repeatedly. Please refer to the format of while statement below.
while condition:
statements
Let us look at an example of “while loop” in Python.
#program to display the numbers from 1 to 7
a=1
while a<=7:
print(a)
a+=1
print("The end")
Output
1
2
3
4
5
6
7
The end
You can also use the “while loop” in many complex situations. For example, let us now write a program to display numbers between 120 and 130
#program to display numbers between 120 and 130
a=120
while a>=120 and a<=130:
print(a)
a+=1
print("the end")
Output
120
121
122
123
124
125
126
127
128
129
130
the end
for loop in Python
In Python, a “for loop” is used to iterate over a sequence of elements. In other words, it means that you can use “for loop” to execute a block of statements repeatedly depending on the number of elements in the sequence. Please refer to the format of “for loop” below.
for var in sequence
statements
During execution, the first component of the sequence is assigned to the variable after “for”, and the statements are executed after that. After this, the second component of the sequence is assigned to the variable, and then the statements are performed for the second time. It means that for each component, the block of statements gets executed once. It also means that you can execute the statements any number of times in “for loop” by specifying it in the code.
Let us look at an example now.
string_a='Laptop'
for c in string_a:
print(c)
print("The end")
Output
L
a
p
t
o
p
The end
In the above program, we declared a variable “string_a” with the value “Laptop” in it. You can see that there are six characters in this declared string. In the following line of code, we declared a variable ‘c’ in the “for loop”. The first character of the declared string, ‘L’, gets stored in the variable c, and the statement gets executed. Since the print statement, print(c) is the only statement in this for loop, it gets executed, and the value stored in the ‘c’ variable during the first iteration gets printed. After this, the value of the ‘c’ variable gets mapped to the second character and prints the second character. This gets repeated in a loop until all the characters in the declared string are printed.
We can also use the concept of “range” in “for loops”. For example, let us now try printing only the odd numbers between 11 and 20 using “range” and “for loop”.
#program to display odd numbers between 11 and 20
for a in range(11,20,2):
print(a)
print("The end")
Output
11
13
15
17
19
The end
We can also use “lists” in “for loop” to obtain our desired output. Let us look at an example that will print all the elements in a list and display the sum using “for loop”.
#discover sum of list of numbers using for loop
list1=[100,200,300,400,500] #declares a list
sum=0 #initializing the sum variable to zero
for num in list1:
print(num)
sum+=num
print("Sum of all the numbers in list: ",sum)
Output
100
200
300
400
500
Sum of all the numbers in list: 1500
Infinite Loops
Infinite loops are one of the disadvantages of a program. Infinite loops are often created in the program without our notice because we don’t really need infinite loops in any program. That would be the last thing a client needs from you as a programmer. The loops that are never terminated are called infinite loops. Let us look at an example below.
i=0
while i<=5:
print(i)
The output of the above program will display 0 infinite times as it satisfies the condition “i<=5”, and therefore it never comes out of the loop. Another intentional way to create an endless loop is by giving the condition itself as True. Let us look at an example below.
while(True):
print("You rock")
Nested Loops
If you add a loop within a loop in a program, it is called a Nested Loop. For example, we can write a “for loop” within a “for loop” or “for loop” within a “while loop”. They are called Nested loops. Please refer to the examples below.
adjectives=["amazing","wonderful","awesome"]
cities=["Hyderabad","Secunderabad","Suryapet"]
for x in adjectives:
for y in cities:
print(x,y)
Output
amazing Hyderabad
amazing Secunderabad
amazing Suryapet
wonderful Hyderabad
wonderful Secunderabad
wonderful Suryapet
awesome Hyderabad
awesome Secunderabad
awesome Suryapet
You can see that the outer loop is executed first before the execution of the inner loop commenced. And when the outer loop is executed once, the inner loop is performed three times.
You can also use this concept to display the star symbol “*” in a triangular form. Let us now look at a program to understand the same.
for a in range(1,7): #to display 6 rows
for b in range(1, a+1): #number of stars = row number
print("*", end='')
print()
Output
*
**
***
****
*****
******
The else Suite
Python allows you to use the “else statement” along with the “while” or “for” loops, as mentioned in the table below.
In the format shared above, the statements added after the ‘else’ is called a suite. Python will consistently execute the else suite without depending on whether the loop statements are executed or not. Even if the “for loop” is not executed for any condition, the else suite will be executed for sure. Let us look at an example of the “else suite” below.
for a in range(3):
print("Amazing")
else:
print("No")
Output
Amazing
Amazing
Amazing
No
The break statement
We use the “break statement” in python to come out of a “for loop” or “while loop”. For example, let us consider the Python code to iterate the “while loop” statements ten times. However, you want to make the execution come out of the loop after the 8th time. In this case, you would need to add a “break” statement with small logic. Let us look at an example now.
a=14
while(a>=1):
print("a: ",a)
a-=1
if(a==7):
break
print("Out of the loop")
Output
a: 14
a: 13
a: 12
a: 11
a: 10
a: 9
a: 8
Out of the loop
The continue statement
We use the “continue statement” in python to go to the beginning of a loop. In other words, if you use “continue”, the next repetition will commence. Let us look at an example program to understand this concept better.
a=0
while a<10:
a+=1
if a>5: #if a>5, then commence next loop
continue
print("a= ",a)
print("You are outside the loop")
Output
a= 1
a= 2
a= 3
a= 4
a= 5
You are outside the loop
In the above program, as per the “if statement” included within the “while loop”, if the value of variable ‘a’ is greater than 5, it skips the print statement contained in the loop and begins the next iteration. This continues until the variable ‘a’ value is 9, but the output prints only till 5 as per the “if statement” and “continue statement” added within the “while loop”. If you comment the lines 4 and 5 of the program above by including the symbol # at the beginning of those lines, you can see that all numbers above 5 get executed, and the program prints till 10, as shown in the output below.
Output
a= 1
a= 2
a= 3
a= 4
a= 5
a= 6
a= 7
a= 8
a= 9
a= 10
You are outside the loop
The pass statement
The “pass statement” in Python does not have any effect. Unlike the continue statement, the pass statement does not do any operation in any code. For example, if we use “pass” instead of “continue” in the above example, you can see that all the numbers are printed. Let us look at an example now.
a=0
while a<10:
a+=1
if a>5: #if a>5, then commence next loop
pass
print("a= ",a)
print("You are outside the loop")
Output
a= 1
a= 2
a= 3
a= 4
a= 5
a= 6
a= 7
a= 8
a= 9
a= 10
You are outside the loop
We use the “pass” to let the Python interpreter know that we do not depend on the results.
The assert statement
We use the “assert statement” in Python to know if a particular condition is satisfied or not. Please refer to the format below.
assert expression, message
For example, if you want to ensure that the user should enter only positive numbers, you can add an assert statement as mentioned below.
assert a>0, "Please enter positive number"
Let us look at an example now.
#program to illustrate assert statement
a=int(input("Enter a number which is greater than 0: "))
assert a>0,"Please enter positive number"
print("You've entered: ",a)
Output
Enter a number which is greater than 0: -2
Traceback (most recent call last):
File "E:\Python\PythonControlStatements\main.py", line 3, in <module>
assert a>0,"Please enter positive number"
AssertionError: Please enter positive number
-------------------------------------------------------
Enter a number which is greater than 0: 2
You've entered: 2
You can see in the above program that an assertion error was displayed when we entered a negative number, and Python Interpreter didn’t show us the expected results. The output was displayed only when we entered a positive number.
The return statement
A function in python refers to a block of statements to complete any activity. After a function performs its intended action, it returns the result. To understand the return statement better, let us look at an example below.
# a function to find the subtraction result of two numbers
def sub(x,y):
print('Subtraction result: ',x-y)
sub(7,5) #calls the function sub() and passes the values 7 and 5
sub(30,15) #calls the function sub() and passes the values 30 and 15
Output
Subtraction result: 2
Subtraction result: 15
In the above program, we declared a function with “sub” and variables x and y. For those of you who are new to functions, please do not worry. We will explore them in greater detail in our future chapters. Just keep in mind that this is how we add functions to a program. For the function, sub(x,y) that we have added, print(‘Subtraction result: ‘,x-y) is the only statement. And the result is displayed in the output as we added a print statement to the function, not because it returns the computed result.
In some situations, you will find it helpful if the function returns the computed result. You can do so by using the return statement in the format mentioned below.
return expression
Let us rewrite the same program once again using the return statement as mentioned below.
# a program to illustrate the concept of return statement
def sub(x,y):
return x-y #the computed result is returned here
a=sub(7,5)
#calls the function sub() and passes the values 7 and 5
#and stores computed result in variable a
b=sub(30,15)
#calls the function sub() and passes the values 30 and 15
#and stores computed result in variable b
print("Subtraction Result: ",a)
print("Subtraction Result: ",b)
Output
Subtraction Result: 2
Subtraction Result: 15
We hope you have understood the Python Control Statements now.