Ch3. Control Statements
Ch3. Control Statements
Ch3. Control Statements
Those statements will control the flow of program are known as control
statements.
It is of two types
a) Decision Making
b) Looping
1) Python if statement
Here, the condition after evaluation will be either true or false. if the statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not.
As we know, python uses indentation to identify a block. So the block under an
if statement will be identified as shown in the below example:
if condition:
statement1
statement2
As the condition present in the if statement is false. So, the block below the if
statement is executed.
Python3
i = 10
if (i > 15):
Output:
I am Not in if
The block of code following the else statement is executed as the condition
present in the if statement is false after calling the statement which is not in the
block(without spaces).
Python3
#!/usr/bin/python
i = 20
if (i < 15):
print("i'm in if Block")
else:
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
Example of Python if else statement in a list comprehension
Python3
# Explicit function
def digitSum(n):
dsum = 0
dsum += int(ele)
return dsum
# Initializing list
Output :
[16, 3, 18, 18]
In this example, we are showing nested if conditions in the code, All the If
conditions will be executed one by one.
Python3
i = 10
if (i == 10):
# First if statement
if (i < 15):
# Nested - if statement
# it is true
if (i < 12):
else:
Python3
#!/usr/bin/python
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
Output:
i is 20
Python3
i = 10
Output:
i is less than 15
i = 10
Output:
True