Intro to if#
IF#
The if
statement allows the execution of code when certain condition is met (True
).
General syntax
`if` condition:
# body of statement if the condition is True
Caution
Python uses indentation style (i.e., 4 spaces or tabs at the beginning of lines) to define the structure of code statements within loops, functions, and conditional statements
IF/ELSE#
Additionally, you can use the else
statement to specify an alternative block of code to be executed if the condition is False
.
General syntax
if condition:
# Statement to be executed if the condition is true
else:
# Statement to be executed if the condition is false
IF/ELSE/ELIF#
You can also use multiple elif
(i.e., “else if”) statements to specify additional conditions to be checked. The if
, else
, and elif
statements provide a way to control the flow based on specific conditions and executes different blocks, which makes your program more flexible on various situations.
General syntax
if condition1:
# Statement to be executed if the condition1 is true
elif condition2:
# Statement to be executed if the condition1 is False and condition2 is True
else:
# Statement to be executed if all conditions are false
Examples#
# Example 1
x = 10
if x > 0:
print("x is positive")
else:
print("x is non-positive")
x is positive
# Example 2
x = 10
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
x is positive
Nested#
if
statements are placed within the code block of another if
statement, and builds additional decision conditions within the block of code executed when the outer if statement’s condition is true.
General syntax
if condition1:
# Code to be executed if condition1 is true
if condition2:
# Code to be executed if both condition1 and condition2 are true
else:
# Code to be executed if condition1 is true but condition2 is false
else:
# Code to be executed if condition1 is false
# Example 3
number = 5
# outer if statement
if (number >= 0):
# inner if statement
if number == 0:
print('Number is 0')
# inner else statement
else:
print('Number is positive')
# outer else statement
else:
print('Number is negative')
Number is positive