Python If...Else
Conditional Statements
Python uses `if`, `elif`, and `else` statements for conditional execution. These allow your program to make decisions and run different code depending on conditions.
Example
# Basic if statement
x = 10
if x > 5:
print("x is greater than 5")
# If-else statement
if x % 2 == 0:
print("x is even")
else:
print("x is odd")
# If-elif-else statement
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Output
x is greater than 5 x is even Grade: B
Nested If Statements
You can place an `if` statement inside another `if` statement to evaluate more detailed conditions.
Example
# Nested if statements
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive")
else:
print("You need a license to drive")
else:
print("You're too young to drive")
Output
You can drive
Conditional Expressions (Ternary Operator)
For concise conditional assignments, Python supports a shorthand syntax often called the ternary operator.
Example
# Ternary operator
x = 10
y = 20
# Traditional way
if x > y:
result = x
else:
result = y
# Ternary operator way
result = x if x > y else y
print(f"The larger number is: {result}")
# Multiple conditions in shorthand
age = 25
status = "Adult" if age >= 18 else "Minor"
print(f"Status: {status}")
Output
The larger number is: 20 Status: Adult
Boolean Operations with If
Combine multiple conditions using logical operators `and`, `or`, and `not` to create more powerful condition checks.
Example
# Boolean operations with if
age = 25
income = 50000
has_credit = True
if age >= 18 and income > 30000 and has_credit:
print("Loan approved")
else:
print("Loan denied")
# Using 'or' and 'not'
if age < 18 or not has_credit:
print("Additional documentation required")
else:
print("No additional documentation needed")
Output
Loan approved No additional documentation needed