Data Science with Python: Control Flow Statements

control flow statements

Introduction

After learning about the NumPy and Pandas libraries of Python language, it is the correct time to take a deep dive into the working of programs.  In this article, we are going to learn about how a program actually got executed and how the control from one statement of the program passes on to the other statements. Let’s get started.

Control Flow Statements

The control flow, As the name suggests tells us about the flow of control in the Statements of the program, it is the order in which the computer executes statements in a program. Generally, Code is run in order from the first line to the last line. The use of conditional statements will completely change the understanding of the program. Let’s take a look at how all of them work together.

Conditional Statements

In Python, conditional statements work depending on whether a given condition is true or false. They check the given condition to generate the output. These are:

1.     If statements

In control statements, The if statements are the simplest form. It evaluates a condition to be either true or false.  If the condition is true, then the block of code will be executed, and if the condition is False, then the block of code is skipped, and the control is moved to the next line.

Syntax of the if statement:

if condition:
statement 1
statement 2
statement n

Let’s see the example of the if statement. In the example below, we are printing the statement for adding the given number 2 times if the condition is true.

Input Code:

number = 8
if number < 10:
# Calculate sum
print(number + number)
print(‘Next lines of code’)

 

Output:

16
Next lines of code

2.     If Else statements

In the if – else statement, it first checks the condition and executes the  if block of code only when the condition is True, and if the condition is False, then it will execute the else block of code.

Syntax of the if-else  statement:

if condition:
Code block  1
else:
Code block  2

 If the condition is true, then code/ statements of code block 1 will be executed and If the condition is false, statements/code of code block 2 will be executed.

Let’s take an example for the same. In the example below, we are using if-else statement for checking the password.

Input Code:

password = input(‘Enter password ‘)

if (password == “Data_Science”):
print(“Correct password”)
else:
print(“Incorrect Password”)

 

Output 1: When correct password is entered as input

Enter password Data_Science
Correct password

 

Output 1: When incorrect password is entered as input

Enter password datas_science
Incorrect Password

3.     Chain if else statements

In Python, the if-elif-else condition statement has an elif block to chain multiple conditions one after another. This is useful when we want to check multiple conditions. With the help of if-elif-else we can check multiple conditions one by one and if the condition fulfills, then code will be executed. In if-elif-else  statement, there is an if statement inside another if-else statement.

Syntax for if-elif-else:

Statement

If condition-1:
Statement 1
elif condition-2:
Statement 2
elif condition-3:
Statement 3

else:
Statement

In the example below, we are checking the options of user by if-elif-else statements

Input Code:

def user_options(choice):
if choice == 1:
print(“True”)
elif choice == 2:
print(“False”)
elif choice == 3:
print(“Both are correct”)
else:
print(“wrong”)user_options(1)

user_options(1)

user_options(2)
user_options(3)
user_options(4)

 

Output:

True
False
Both are correct
wrong

4.     Nested if-else statement

In Python, the nested if-else statement is basically an if statement inside another if-else statement. It is allowed in Python language to put any number of if statements inside another if statement. The nested if-else is useful when we want to make a series of decisions and using only if-else  is not worth

Syntax of nested if-else:

if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement of outer if
else:
Outer else
statement outside if block

Example for finding the larger number between two numbers using nested if-else  statements.

Input Code:

n1 = int(input(‘Enter first number ‘))
n2 = int(input(‘Enter second number ‘))

if n1 >= n2:
if n1 == n2:
print(n1, ‘and’, n2, ‘are equal’)
else:
print(n1, ‘is greater than’, n2)
else:
print(n1, ‘is smaller than’, n2)

 

Output 1: When first inner if loop got executed:

Enter first number 56
Enter second number 15
56 is greater than 15

 

 Output 2 : When the outer if loop got executed:

Enter first number 29
Enter second number 78
29 is smaller than 78

Iterative Statements

In Python, iterative statements allow us to run a block of code/part of a program again and again as long as the condition is True. We also call it loop statements. They are also known as loop statements. In Python, iterative statements allow us to execute a block of code in a program again and again as long as the condition is True. The control came out of the code block when conditions become false.

1.     For loop :

In Python, the for loop is used to iterate over a sequence for a list, string, tuple. With the help of a for loop, we can iterate over each item present in the sequence and execute the same set of operations for each item. Using a  for loop in Python we can repeat tasks in an efficient manner.

Syntax:

for element in sequence:
body of for loop

Let’s take an example to understand this loop, in this example we are printing the square of numbers by the help of for loop.

Input Code:

numbers = [1, 2, 3, 4, 5]
# iterate over each element in list num
for i in numbers:
square = i ** 2      # ** exponent operator
print(“Square of:”, i, “is:”, square)

 

Output:

Square of: 1 is: 1
Square of: 2 is: 4
Square of: 3 is: 9
Square of: 4 is: 16
Square of: 5 is: 25

2.     While loop in Python

In Python, The while loop statement executes again and again for a code block until the particular condition is true.

In a while-loop, every time the condition of the program is checked at the beginning of the loop, and if it is true, then the loop’s body gets executed. When the condition becomes False, the controller comes out of the code block.

Syntax for while loop:

while condition :
body of while loop

In this Example, we are printing the sum of the first 10 numbers using while  statement.

Input Code:

num = 10
sum = 0
i = 1
while i <= num:
sum = sum + i
i = i + 1
print(“Sum of first 10 number is:”, sum)

 

Output:

Sum of first 10 number is: 55

Transfer statements

In Python, we use transfer statements to change the way of execution of a program in a certain manner. For this purpose, we use three types of transfer statements.

1.     Break

The break statement is used inside the loop to come out of the loop. In Python, when a break statement is written inside a loop, the loop terminates, and the program control transfers to the next statement following the loop. In simple words, A break keyword terminates the loop containing it.

Syntax:

Break

Example of using Break  statement:

Input Code:

for num in range(10):
if num > 5:
print(“stop processing.”)
break
print(num)

 

Output:

0
1
2
3
4
5
stop processing.

2.     Continue statements in Python

Continue statement is a part of the transfer statement. The continue statement ends the flow of iteration and skip it and continue with the next iteration.

Let’s take one example to understand.

In this example, we tried to reflect how to skip a for a loop iteration if the number is 5 and continue executing the body of the loop for other numbers.

Input Code:

for num in range(3, 8):
if num == 5:
continue
else:
print(num)

 

output:

3
4
6
7

3.     Pass statement in Python

The pass is the keyword In Python, which does not do anything. Sometimes there is a situation in programming where we need to define an empty block. We can define that empty block with the “  pass “ keyword.

A Pass statement is equivalent to a null statement. When the interpreter encounters a pass statement in the program, it returns no operation. Nothing happens when the  pass statement is executed. The program will follow its usual path.

Input Code:

months = [‘Dec’, ‘June’, ‘Sep’, ‘Oct’]
for mon in months:
pass
print(months)

 

Output:

[‘Dec’, ‘June’, ‘Sep’, ‘Oct’]

Conclusion

In this article we tried to cover all control flow statements with examples. From this article, now we all are aware of how a program gets executed and interpreted inside computers and how the control is transferred.

Stay Tuned!!

Learn the basics of Data Science in Data Science with Python series.

Keep learning and keep implementing!!

Leave a Comment

Your email address will not be published. Required fields are marked *