Condtional Statements: IF If-Else Nested If
Condtional Statements: IF If-Else Nested If
IF
IF-ELSE
NESTED IF
if test expression:
statement(s)
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
Output:
3 is a positive number
This is always printed
This is also always printed.
IF ELSE
Syntax of if...else
if test expression:
Body of if
else:
Body of else
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Output:
Positive or Zero
If..elif…else
• The elif is short for else if.
• It allows us to check for multiple expressions.
• If the condition for if is False, it checks the condition of the
next elif block and so on.
• If all the conditions are False, body of else is executed.
• Only one block among the several if...elif...else blocks is
executed according to the condition.
• The if block can have only one else block. But it can have
multiple elif blocks.
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output:
Positive or Zero
Nested if statements
• We can have a if...elif...else statement inside
another if...elif...else statement. This is called nesting in
computer programming.
• Any number of these statements can be nested inside one
another. Indentation is the only way to figure out the level of
nesting.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number") Output:
else: Enter a number: 5
print("Negative number") Positive number
Python Indentation
Nesting indicated by indentation
Python uses indentation to show block structure.
Indent one level to show the beginning of a block.
if x:
if y:
f1()
f2()
The while statement
• The while loop in Python is used to iterate over a block of
code as long as the test expression (condition) is true.
• Used for repeating an action or set of actions
• We generally use this loop when we don't know beforehand,
the number of times to iterate.
while test_expression:
Body of while
• In while loop, test expression is checked first. The body
of the loop is entered only if the test expression evaluates
to True. After one iteration, the test expression is
checked again. This process continues until the test
expression evaluates to False.
• Here, val is the variable that takes the value of the item inside
the sequence on each iteration.
• Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code
using indentation.
Flowchart of
for Loop
Example: Python for Loop
for x in "banana":
print(x)
b
a
n
a
n
a
# Increment the sequence with 3 (default is 1):