Python If...Else
Conditional statements in Python allow your program to make decisions and execute different blocks of code based on whether a condition evaluates to True or False. Python uses if, elif, and else keywords along with indentation to define code blocks.
1. The if Statement
An if statement evaluates a test expression and executes the indented block only when the condition is True:
age = 20
if age >= 18:
print("You are eligible to vote.")
2. Using elif and else
Use elif ("else if") to check multiple conditions in sequence, and else as a fallback when none of the previous conditions are True:
marks = 78
if marks >= 90:
print("Grade: A+")
elif marks >= 75:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
else:
print("Grade: C")
3. Short-Hand If...Else (Ternary Operator)
When you have only one statement to execute for if and one for else, you can write it cleanly on a single line:
num = 15
status = "Even" if num % 2 == 0 else "Odd"
print(status) # Output: Odd
4. Combining Conditions with Logical Operators
You can combine multiple conditions using and, or, and not:
is_logged_in = True
is_admin = False
if is_logged_in and is_admin:
print("Welcome to Admin Dashboard")
elif is_logged_in and not is_admin:
print("Welcome, User!")
else:
print("Please log in first.")
5. Nested if Statements
You can place an if statement inside another if statement to check secondary conditions:
has_ticket = True
age = 16
if has_ticket:
if age >= 18:
print("Entry allowed to the concert.")
else:
print("Entry allowed only with an adult.")
else:
print("Please buy a ticket first.")
{} to define the scope of if, elif, and else blocks. Missing indentation will raise an IndentationError.