Unit02_Control Statements (1)
Unit02_Control Statements (1)
1. Python if statement
Syntax:
if condition:
# Statements to execute if
# condition is true
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.
Flowchart of Python if statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Output:
I am Not in if
2. Python If-Else Statement
The if statement alone tells us that if a condition is true, it will execute a block of
statements and if the condition is false, it won’t.
But if we want to do something else if the condition is false, we can use the else
statement with the if statement to execute a block of code when the if condition is
false.
if (condition):
# condition is true
else:
# condition is false
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
3. Nested-If Statement in Python
“Yes, Python allows us to nest if statements within if statements. i.e., we can place
an if statement inside another if statement.”
Syntax:
if (condition1):
if (condition2):
Else:
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
4. Python if-elif-else Ladder
Here, a user can decide among multiple options.
As soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final “else” statement will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
else:
statement
Flowchart of Python if-elif-else ladder
Let’s look at the flow of control in if-elif-else ladder:
Example of Python if-elif-else ladder
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
PROGRAMS:
factorial = 1
if num <0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("Factorial of 0 is 1")
else: