Conditional Statements in Python

Conditional Statements in Python

Conditional statement in Python

In this article, we will discuss about the structure of conditional statements with examples in python and how we can change the flow of program using these statements. We will also understand the loop statements which are used to iterate a statement or a block of code several number of times. Also discuss about break statement, continuous statement, nested loops, etc. 

Learning objectives:

  • Describe the conditional statements in python
  • Write conditional statements to control the flow of code
  • Define loops and their types in python
  • Understand why loops are useful 
  • Recall the need of indentation
  • Describe the range function
  • Learn about break and continue statements 
  • Implement a mix of loops

When a program executes, the interpreter always keep track of which statement is about to be executed. We call this the control flow or the flow of execution of the program. When humans execute programs, they often use their finger to point to each statement in turn. So we could think of control flow as a “Python’s moving. finger”. Control flow until now has been strictly top to bottom, one statement at a time. We can change the control flow program by making use of conditional statements and loops in Python. 

The conditional statements are used where we may have to change the order of execution of the statements depending on some specific conditions. It involves a kind of decision making based on upon the result of certain conditions. Python have different type of conditional statements like if, if-else, elif etc. 

Note: Python interprets any non-zero value as True and zero or null value as false. 

1.1 Conditional statement in Python If statement: 

If statement is used to execute statement(s) only if certain condition is satisfied. The syntax for an if statement looks like this. 

#Syntax for an if statement
if expression:
statement(s) # Executed if condition evaluates to True

The indented statements that follow are called a block. The first unindented statement marks the end of the block. 

Flow chart of if statement:

In this case, when the condition evaluates to True, the statement(s) are executed, otherwise the flow of execution continues to this statement after the body of if statement. In Python, the body of the if statement is indicated by the statement(s) with equal indentation.

Example: 

#Program for demonstration of if statement
n = int(input(“Enter a number:”))
if n<5:
print(n, “is less than 5”)

Output 1:

Enter a number: 2
2 is less than 5
Output 2:
Enter a number:11
>>>

1.2 Conditional statement in Python If-else statement:

It is used to execute statement(s) when certain condition is satisfied and other statement(s) if that condition fails. The syntax for an if-else statement looks like this: 

#Syntax for an if statement
if expression:
statement (s) # Executed if condition evaluates to True
else:
statement (s) # Executed if condition evaluates to False

If first expression evaluates to True, then statement(s) of only if statement will be executed and if it evaluates to False, then statement(s) under the else statement will be executed. 

Flow chart of if-else statement: 

Example:

#Program for demonstration of if-else statement
n = int(input(“Enter a number:”))
if n < 5:
print (n, “is less than 5”)
else:
print(n, “is not less than 5”)

Output 1:

Enter a number: 3
3 is less than 5

Output 2:

Enter a number:15
15 is not less than 5

1.3 Conditional statement in Python ELSE IF STATEMENT:

Sometimes there are more than two groups of statements, in this situation we would like to execute only one group of statements from more than two groups of statements. In Python, this can be achieved with the help of elif statement. It allows us to check for multiple expressions. The syntax for an if-else statement looks like this:

#Syntax for an else if statement

if expression_1:
statement(s) # Executed if expression_1 evaluates to True
else if expression 2:
statement(s) # Executed if expression_1 evaluates to False
else:
statement(s) # Executed if all the above expressions are evaluated to False

Here, exactly one group of statement(s) will be executed. We can include any number of else if statements in code but only a single final else statement is allowed and it must be the last branch in the statement. Each condition is checked in order. If first one is false then next is checked and so on. If one of them is true, then corresponding statement(s) get executed ends. Even if more than one condition is true, only the first true expression executes.

Flow chart of else if statement:

Example: 

# Program for the demonstration of else if statement
n = int (input(“Enter a number:”))
if n<5:
print (n,”is less than 5″)
else if n>5:
print (n, “is greater than 5”)
else:
print (n,” is equal to 5″)

Output 1:

Enter a number: 4
4 is less than 5

Output 2:

Enter a number: 6
6 is greater than 5

Output 3:

Enter a number: 5
5 is equal to 5
1.4 Conditional statement in Python NESTED IF-ELSE STATEMENT:

Nesting of control statements means when an if statement (or if-else) is presented inside another if statement (or if-else). These nested control statements allows us to check multiple conditions one after another (one by one). Here we have an if-else statement inside another if-else statement block. Following is the syntax for nested if-else statement. 

#Syntax for nested if-else statement
if expression:
if expression:
statement (s)
else:
statement (s)
else:
if expression:
statement(s)
else:
statement(s)

Example:

# Program for the demonstration of else if statement
n = int(input(“Enter a number”))
if n < 5:
print(n,”is less than 5″)
else if n>5:
print(n,”is greater than 5″)
else:
print(n,”is equal to 5″)

Output 1:

Enter a number: 4
4 is less than 5

Output 2:

Enter a number: 6
6 is greater than 5

Output 3:

Enter a number: 5
5 is equal to 5

1.5 Conditional statement in Python PURPOSE OF LOOP STATEMENTS:

In general, statements are executed sequentially but there may be a situation where we need to execute a block of code several number of times. Here, the concept of loop statements comes into a picture. Loop statements are used to execute a statement or a group of statements repeatedly either number of times or till a particular condition is satisfied.

Python supports two kinds of loop statements: For loop statement and While loop statement. 

1.6 Conditional statement in Python FOR LOOP STATEMENT:

A for loop statement is used to iterate in a sequence. A for loop in Python requires at least two variables to work. The 1st is the variable to store the successive values from the sequence in the loop and second refers to any of the following. Python objects such as a list, a tuple, or a string. The syntax of for loop statement looks like this: 

#Syntax for for loop in python
for variable in sequence:
statement(s) # Body of loop that has set of statements
# which requires repeated execution

Each iteration assigns the value in variable from the sequence one by one and then executes the statements in the body. The loop terminates when the last element in the sequence is reached. 

Flow chart of for loop: 

Before executing the code inside the loop, the value from the sequence get assigned to the iterating Variable. 

Example:

Below example shows the use of for loop to iterate over a list of numbers. This code calculates the square of each number present in list and displaying the same. 

# Program for the demonstration of for loop over a list of numbers
# print squares of all numbers present in a list

# List of integer numbers
numbers = (1, 2, 3, 4, 5, 6)

#Variable to store the square of each num
sq = 0

# iterating over the given list
for val in numbers:
# calculating square of each number
sq = val * val
# displaying the squares
print(sq)

Output:

1
4
9
16
25
36

Use of range() function in for loop: 

In the above example, we have iterated over a list using for loop. However, we can also make use of a range() function in for loop to iterate over numbers defined by range(). 

Case 1: 

range(n): Generates a set of whole number starting from 0 to (n -1). For example: range(8) is equivalent to [0,1, 2, 3, 4, 5, 6, 7]  

Case 2: 

range(start,stop): Generates a set of whole numbers starting from start to stop 1. For example: range (5,9) is equivalent to [5, 6, 7, 8]. 

Case 3:

range(start, stop, step_size): When we did not specify the step_size, the numbers generated are having difference of 1 because by default the value of the step_size is 1. We can change it as per our need. For example: range(1, 10, 2) is equivalent to [ 1, 3, 5, 7, 9]. 

for Loop example using range() function:

Here we are using range() function to calculate and display the sum of first 5 natural numbers. 

# Program for the demonstration of for loop using range() function
# Program to print the sum of first 5 natural numbers

sum = 0 # variable to store the sum
for val in range(1,6): # iterating over natural numbers using range()
sum = sum + val # calculating sum
# displaying sum of first 5 natural numbers
print(sum, “is the sum of first 5 natural number”)

Output:

15 is the sum of first 5 natural numbers

1.7 Conditional statement in Python WHILE LOOP STATEMENT:

While loop statement is used to repeat a statement or group of statements until a given condition returns false. When we are not certain about the number of times of loop requires execution, we will make use of while loop.  

For example: We want to count the occurrence of even numbers in a given range. On the other hand, when we exactly know how many times we need to run the loop, we use for loop, we use for loop. It is also called pre-test loop as it first checks the condition before each iteration. If the check fails, then the control won’t enter into the loop. Instead it will get transferred to the next statement after the loop. The syntax of while loop statement look like this:

#Syntax for while loop in python
while condition:
statement(s) # Body of loop that has set of statements
# which requires repeated execution

Statement(s) in the body of while loop will execute till the expression or condition gives True i.e. till condition is satisfied. 

Flow chart of while loop:

 Example:

This code print the reverse of a given number by using while loop.

# Program for the demonstration of while loop
# Program to print the reverse of a given number
# loop will repeat itself until n != 0
n = int(input(“Enter the number:”) #variable to store the number
while n !=0:
d n% 10
print(d, end=””) # (end= “”) is used to print the output in a single line
n //= 10

Output:

Enter the number: 123
321

Examples of infinite while loop:

Example 1. This will print the word ‘Hello Learner’ indefinitely because the condition will always be true. 

# Program for the demonstration of infinite while loop
while True:
print(“Hello Learner”)

Example 2. This will print ‘1’ indefinitely because inside the loop we are not updating the value of num, so the value of num will always remain 1 and the condition num<5 will always return true. 

# Program for the demonstration of infinite while loop
num = 1
while num<5:
print (num)

1.7 Conditional statement in Python BREAK STATEMENT:

The break statement is used to terminate the loop execution immediately. It brings the program flow to the statement just after the body of loop. It can be used in both while loop and for loop. It is commonly used in situation when some external condition is triggered, requiring a hasty exit from a loop.  

In case of nested loops, break statement is stops the execution of innermost loop and start the next line of code after that block. 

Syntax:

# syntax of break statement
break

Working of break statement in for loop: 

#working of break statement in for loop
for var is sequence:
#code inside for loop
if condition:
break
#code inside for loop
#code outside for loop

Working of break statement in while loop:

#working of break statement in while loop
while text expression:
#code inside while loop
if condition:
break
#code inside while loop
#code outside while loop

Example:

In this program, we iterate through the “hello” sequence. Here we will check if the letter “e” is there in the sequence, then we will come out of the loop. Hence, we can see in output that all the letters “e” gets printed. After that the loop terminates. 

# Program for the demonstration of break statement inside for loop
for val in “hello”
if val == “e”:
break
print (val)
print (“The end”)

Output:

# Program for the demonstration of break statement inside for loop
for val in “hello”
if val == “e”:
break
print (val)
print (“The end”)

1.8 Conditional statement in Python Continue statement: 

The continue statement is used to skip the loop single statement or group of statements execution for the current iteration. Loop does not terminate, it will continues with the next iteration. 

Syntax:

# syntax of continue statement
continue

Working of continuous statement in for loop: 

#working of continue statement in for loop
for var in sequence:
#code inside for loop
if condition:
continue
#code inside for loop
#code outside for loop

Working of continue statement in while loop:

#working of continue statement in while loop
while text expression:
#code inside while loop
if condition:
continue
#code inside while loop
#code outside while loop

Example:

This program is same as above example except the break statement has replaced with continuous statement. Here, if the letter “e” is there in sequence then it is skipped by the interpreter, but loop does not terminate, it continues with the next iteration. Hence, we can see in output that all the letters except “e” gets printed. 

# Program for the demonstration of continue statement inside for loop
for val in “hello”:
if val == “e”:
continue
print(val)
print (“The end”)

Output:

h
1
1
0
The end

1.9 Conditional statement in Python ELSE STATEMENT WITH LOOPS

In Python, we can associate else statement with loop statement. The else statement can be used to find out loop is executed completely or not because the else statement with loop is executed only if loop is terminated after complete execution. Note due to break statement. 

Example: 

This program shows the use of else statement in for loop. 

# Program for the demonstration of else statement inside for loop
for i in range (1,4):
print (i)
else:
print (“Out for Loop”)

Output:

1
2
3
Out of Loop

1.10 Conditional statement in Python NESTED LOOP:

When we put a loop inside a loop then we call it a nested loop. It is used to repeat loop. 

Syntax of nested for loop is:

# syntax of nested for loop
for variable in sequence:
for variable in sequence:
statement (s) #Body of inner for loop
statement (s) #Body of outer for loop

Syntax of nested while loop is:

# syntax of nested while loop
while expression:
while expression:
statement (s) #Body of inner for loop
statement (s) #Body of outer for loop

Python allows nesting of mix loops. For example, A for loop can be inside a while loop or while loop can be inside a for loop. 

Example: 

# Program for the demonstration of nested for loop
for i in range (1,11):
for j in range (1,11):
k = i * j
print (k, end=” “)
print ()

Output:

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

Frequently Asked Questions (FAQs). 

  1. Differentiate between while loop and for loop. 
  2. List the types of conditional statements in Python. 
  3. What do you mean by nested loops? 
  4. Draw the flow of execution for a while statement. 
  5. Illustrate the different types of control statements available in Python with flow charts. 
  6. Explain the need for continue and break statements. Write program to check whether a given number is prime or not. Prompt the user for input. 
  7. Write a program to find entered number is prime or not. 
  8. Write the program to find entered number is palindrome or not. 
  9. Write a program to print palindrome numbers between 100 to 200. 
  10. Explain the purpose of loop statements and their types in Python. 

Conditional Statements in Python

Read More: https://digitalcomputereducation.com/fundamentals-of-python-programming/

Know More: https://www.youtube.com/watch?v=ceiuLR2ysas

Leave a Comment