Control Structures in Python
Control Structures in Python
The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times.
For this purpose, The programming languages provide various types of loops which are capable
of repeating some specific code several numbers of times. Consider the following diagram to
understand the working of a loop statement.
Advantages of loops
There are the following advantages of loops in Python.
Loop Description
Statement
for loop The for loop is used in the case where we need to execute some part of the code
until the given condition is satisfied. The for loop is also called as a per-tested
loop. It is better to use for loop if the number of iteration is known in advance.
while loop The while loop is to be used in the scenario where we don't know the number of
iterations in advance. The block of statements is executed in the while loop
until the condition specified in the while loop is satisfied. It is also called a pre-
tested loop.
do-while The do-while loop continues until a given condition satisfies. It is also called
loop post tested loop. It is used when it is necessary to execute the loop at least once
(mostly menu driven programs).
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
The for loop does not require an indexing variable to set beforehand.
Example
for x in "banana":
print(x)
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.
Example
for x in range(6):
print(x)
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
Example
The range() function defaults to increment the sequence by 1, however it is possible to specify
the increment value by adding a third parameter: range(2, 30, 3):
Example
Example
i=1
while i <= 6:
print(i)
i += 1#equivalent to i=i+1
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.
3. Pass Statement - The pass statement is used to declare the empty loop. It is also used to
define empty class, function, and control statement. Let's understand the following example.
Example -
1. # An empty loop
2. str1 = 'javatpoint'
3. i = 0
4.
5. while i < len(str1):
6. i += 1
7. pass
8. print('Value of i :', i)
Output:
Value of i : 10
1. i=1
2. #The while loop will iterate until condition becomes false.
3. While(i<=10):
4. print(i)
5. i=i+1
1. i=1
2. number=0
3. b=9
4. number = int(input("Enter the number:"))
5. while i<=10:
6. print("%d X %d = %d \n"%(number,i,number*i))
7. i = i+1
Any non-zero value in the while loop indicates an always-true condition, whereas zero indicates
the always-false condition. This type of approach is useful if we want our program to run
continuously in the loop without any disturbance.
Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop")
Example 2
1. var = 1
2. while(var != 2):
3. i = int(input("Enter the number:"))
4. print("Entered value is %d"%(i))
Example 1
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. else:
6. print("The while loop exhausted")
Example 2
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. if(i==3):
6. break
7. else:
8. print("The while loop exhausted")
In the above code, when the break statement encountered, then while loop stopped its execution
and skipped the else statement.
1. terms = int(input("Enter the terms "))
2. # first two intial terms
3. a = 0
4. b = 1
5. count = 0
6.
7. # check if the number of terms is Zero or negative
8. if (terms <= 0):
9. print("Please enter a valid integer")
10. elif (terms == 1):
11. print("Fibonacci sequence upto",limit,":")
12. print(a)
13. else:
14. print("Fibonacci sequence:")
15. while (count < terms) :
16. print(a, end = ' ')
17. c = a + b
18. # updateing values
19. a = b
20. b = c
21.
22. count += 1
The break is commonly used in the cases where we need to break the loop for a given condition.
1. #loop statements
2. break;
Example 1
1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");
Example 2
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);
Output:
Example 3
1. n=2
2. while 1:
3. i=1;
4. while i<=10:
5. print("%d X %d = %d\n"%(n,i,n*i));
6. i = i+1;
7. choice = int(input("Do you want to continue printing the table, press 0 for no?"))
8. if choice == 0:
9. break;
10. n=n+1
Syntax
1. #loop statements
2. continue
3. #the code to be skipped
Flow Diagram
Example 1
1. i = 0
2. while(i < 10):
3. i = i+1
4. if(i == 5):
5. continue
6. print(i)
Output:
Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value 5
from the code.
Python Pass
In Python, the pass keyword is used to execute nothing; it means, when we don't want to execute
code, the pass can be used to execute empty. It is the same as the name refers to. It just makes the
control to pass by without executing any code. If we want to bypass any code pass statement can
be used.
It is beneficial when a statement is required syntactically, but we want we don't want to execute
or execute it later. The difference between the comments and pass is that, comments are entirely
ignored by the Python interpreter, where the pass statement is not ignored.
Suppose we have a loop, and we do not want to execute right this moment, but we will execute
in the future. Here we can use the pass.
1. # pass is just a placeholder for
2. # we will adde functionality later.
3. values = {'P', 'y', 't', 'h','o','n'}
4. for val in values:
5. pass
Example - 2:
1. for i in [1,2,3,4,5]:
2. if(i==4):
3. pass
4. print("This is pass block",i)
5. print(i)
Control Structures
Python If-else statements
Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is true, a
block of code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also
Statement provides the block of the code for the false case of the condition to be checked.
If the condition provided in the if statement is false, then the else statement
will be executed.
Nested if Nested if statements enable us to use if ? else statement inside an outer if
Statement statement.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.
1. if expression:
2. statement
Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")
4. else:
5. print(“the number is odd”)
6.
1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
4. if a>b and a>c:
5. print("a is largest");
6. if b>a and b>c:
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
1. age = int (input("Enter your age? "))
2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. print("Sorry! you have to wait !!");
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");
Example 2
1. marks = int(input("Enter the marks? "))
2. if marks > 85 and marks <= 100:
3. print("Congrats ! you scored grade A ...")
4. elif marks > 60 and marks <= 85:
5. print("You scored grade B + ...")
6. elif marks > 40 and marks <= 60:
7. print("You scored grade B ...")
8. elif (marks > 30 and marks <= 40):
9. print("You scored grade C ...")
10. else:
11. print("Sorry you are fail ?")