Python If…Else Statements

Conditions

Conditional statements are used to execute different code blocks based on different conditions

if Statement

Executes code block if condition is True

   # Basic if statement
   age = 18
   if age >= 18:
       print("You are eligible to vote!")

   # With comparison operator
   temperature = 30
   if temperature > 25:
       print("It's a hot day")

else Statement

Executes code block when if condition is False

   age = 15
   if age >= 18:
       print("Eligible to vote")
   else:
       print("Not eligible to vote")

elif Statement

Handles multiple conditions sequentially

   score = 85
   if score >= 90:
       grade = 'A'
   elif score >= 80:
       grade = 'B'
   elif score >= 70:
       grade = 'C'
   else:
       grade = 'F'
   print(f"Your grade: {grade}")

Nested Conditions

if statements inside other if statements

   num = 15
   if num > 0:
       print("Positive number")
       if num % 2 == 0:
           print("Even number")
       else:
           print("Odd number")
   else:
       print("Non-positive number")

Logical Operators

and Operator

True if both conditions are True

 age = 25
 income = 50000
 if age >= 18 and income > 30000:
     print("Eligible for loan")

or Operator

True if at least one condition is True

 is_student = True
 is_senior = False
 if is_student or is_senior:
     print("Eligible for discount")

not Operator

Reverses the logical state

 is_raining = False
 if not is_raining:
     print("Enjoy outdoor activities")

Ternary Operator

Short-hand for simple if-else statements

 # Syntax: [on_true] if [condition] else [on_false]
 age = 20
 status = "Adult" if age >= 18 else "Minor"
 print(status)  # Output: Adult

Common Mistakes

❌ Common Errors
  • Using assignment (=) instead of equality (==)
  • Forgetting colons at end of condition lines
  • Inconsistent indentation
  • Overlooking case sensitivity
✅ Best Practices
  • Use meaningful condition names
  • Avoid deep nesting (use functions)
  • Order conditions logically
  • Use parentheses for complex conditions
Important Notes:
  • Python uses indentation (whitespace) to define code blocks
  • Conditional expressions evaluate to True/False
  • Empty code blocks need pass statement
Truth Value Testing:

In Python, these evaluate to False:

  • Zero numeric values
  • Empty sequences/collections
  • None
  • False