What is an If-Else Statement?
In Python, if-else statements are used to control the flow of execution based on conditions.
Python evaluates the condition, and based on the result (True
or False
), executes the corresponding block of code.
1. Basic If Statement
The if
statement checks a condition and executes the indented block if it’s True
.
age = 18 if age >= 18: print("You are eligible to vote!") # Output: You are eligible to vote!
2. If-Else Statement
The else
block runs if the condition in the if
statement is False
.
age = 16 if age >= 18: print("You are eligible to vote!") else: print("You are not eligible to vote.") # Output: You are not eligible to vote.
3. If-Elif-Else (Multiple Conditions)
Use elif
(short for “else if”) to check multiple conditions.
score = 85 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") # Output: Grade: B elif score >= 70: print("Grade: C") else: print("Grade: F")
4. Nested If Statements
You can use if statements inside another if statement (nested if) for more complex conditions.
age = 20 has_id = True if age >= 18: if has_id: print("You can enter the club.") # Output: You can enter the club. else: print("You need an ID to enter.") else: print("You are underage.")
Short-Hand If and If-Else
Python allows a compact one-liner for simple if statements.
Short-Hand If
num = 10 if num > 0: print("Positive number") # Output: Positive number
Short-Hand If-Else
num = 10 print("Positive") if num > 0 else print("Negative") # Output: Positive
Logical Operators in If Statements
You can use logical operators like and
, or
, and not
to combine conditions.
age = 22 has_license = True if age >= 18 and has_license: print("You can drive.") # Output: You can drive.