In Python, if-else
statements are used for decision-making. They allow you to execute certain pieces of code based on whether a certain condition is true or false
.
Syntax of if-else Statement:
if condition: # block of code to be executed if the condition is true else: # block of code to be executed if the condition is false
Basic if-else Statement
# Checking if a number is positive or negative num = 10 if num >= 0: print("Number is positive or zero") else: print("Number is negative")
Here -
num >= 0
is the condition being checked.
If num is greater than or equal to zero, "Number is positive or zero" will be printed.
Otherwise, "Number is negative" will be printed.
Nested if-else
Statements
# Checking if a number is positive, negative, or zero num = -5 if num > 0: print("Number is positive") elif num == 0: print("Number is zero") else: print("Number is negative")
Here -
The condition num > 0
is checked first.
If true, "Number is positive" is printed.
If false, the elif num == 0
condition is checked.
If num equals zero, "Number is zero" is printed.
If both conditions are false, "Number is negative" is printed.
# Checking multiple conditions using logical operators num = 7 if num % 2 == 0 and num > 0: print("Number is positive and even") elif num % 2 != 0 and num > 0: print("Number is positive and odd") elif num == 0: print("Number is zero") else: print("Number is negative")
Here -
The and operator (and) is used to combine conditions.num % 2 == 0
checks if num is even.num % 2 != 0
checks if num is odd.num > 0
checks if num is positive.
The elif
statement allows us to check multiple conditions sequentially until one is true.
if-else with Ternary Operator (Conditional Expression)
# Ternary operator usage a = 10 b = 20 max_num = a if a > b else b print("Maximum number is:", max_num)
Here -
The ternary operator
(a if condition else b) allows us to assign a value to max_num based on a condition (a > b).
If a is greater than b, max_num will be assigned a, otherwise b.
Properties of if-else Statements:
- Decision-making -
if-else
statements help in making decisions based on conditions. - Flexibility - You can use if, elif (short for "else if"), and else together to handle multiple cases.
- Nested Statements - You can nest if-else statements within each other to handle more complex scenarios.
- Ternary Operator - Python also supports a concise ternary operator for simple conditional assignments.
Understanding if-else statements is fundamental in programming as they allow you to control the flow of your code based on various conditions, making your programs more dynamic and responsive.