Learn to control the flow of a Python program using
if...elseif statements. This process is also called decision making.
if statement is executed only if a certain condition is True. The the condition is False, then
else statement is executed, if provided in the program.
Python if…else statement is written with
if keyword and
In this Python program, we are comparing the values of
y using the conditional expression
'x < y'.
x = 100 y = 200 if x < y: print('x is less than y') else: print('x is greater than y')
1.2. Condition Expressions
We can write the condition expressions in following ways:
- x is ‘equals to’ y:
x == y
- x is ‘not equals to’ y:
x != y
- x is ‘less than’ y:
x < y
- x is ‘less than or equal to’ y:
x <= y
- x is ‘greater than’ y:
x > y
- x is ‘greater than or equal to’ y:
x >= y
Also note that Python evaluates non-zero values as
0 are interpreted as
1.3. Combining Expressions
To combine the two expressions, Python provides to logical operators:
and: Logical AND
or: Logical OR
x = 100 y = 200 z = 300 if x < y and y < z: print('y lies between x and z') else: print('y lies outside x and z')
2. Elif Statements
elif statement is short form of
else if statements in other programming languages such as Java. A
Elif statement contain a conditional expression which will be executed if it’s previous conditional expression is evaluated to False.
In this Python example, x is greater than y, so the
if statement will be False. So, the Python will execute the
elif statement which is True.
x = 400 y = 200 z = 300 if x < y: print('x is less than y') elif y < z: print('y is less than z')
y is less than z
Python uses indentation to define the scope in the code. (Similar to curly brackets in Java). So be mindful of indentation while writing if else statements in Python.
x = 400 y = 200 z = 300 if x < y: print('x is less than y') elif y < z: print('y is less than z') else: print('Something else')
4. Nested if…else
if...else statement written inside another
if...else statement is called
Be very carefull about indentation while writing nested if statements.
x = 100 y = 200 z = 300 if x < y: if x < z: print('x is less than y and z') else: print('Something else')
5. Empty if Statement
A Python program cannot have an empty
if statement. If for any reason, you must provide an empty
if statement then use the
x = 100 y = 200 if x < y: pass
Happy Learning !!