Python Conditional Statements
Almost in every program it is necessary to execute code only under certain conditions.
To be able to do this, the following conditional statements are available in Python:
- if
- if..else
- Nested if
- if-elif statements
Python if Statement
The if statement is the simplest conditional instruction: it executes inner block of instructions only if the condition is evaluated True.
if condition:For example:
a = 10
if a > 15:
print(f"{a} is greater than 15")
a = -1
if a > 15:
print(f"{a} is greater than 15")
print("The end")Output
10 is greater than 15
The endPython if-else Statement
The if..else statement evaluates a condition and executes the inner instruction block of if only if the test condition is True. Otherwise, if the condition is False, the inner instruction block of else is executed.
if condition:
else:For example:
a = 10
if a % 2 == 0:
print("Even number")
else:
print("Odd number")Python if-elif-else Statement
elif stands for else if: it allows you to check for multiple expressions.
if condition:
elif condition:
..
..
..
else:- If the condition of
ifisFalse, check the condition of the next blockelifand so on. - If all the conditions are
False, the inner instruction block ofelseis executed.
For example:
num = 1.2
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")where:
- if
numis positive,Positive numberis printed. - If
numis equal to 0,Zerois printed. - If
numis negative,Negative numberis printed.
Python Nested If
if...elif...else statement can be nested inside another if...elif...else statement.
if condition1:
if condition2:For example:
num = int(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")And some output with different numbers:
Enter a number: 10
Positive numberEnter a number: 0
ZeroEnter a number: -5
Negative numberShorthand if and if-else
Shorthand if and if-else are if statements that are written on the same line as the if statement.
They are known as Conditional Expressions (or Ternary Operators) and are discussed in detail in the dedicated chapter.
if a > b: print("a is greater than b")
a = 1
b = 10
print("a") if a > b else print("b")