08

Day 8: Conditional Statements

Chapter 8 • Beginner

40 min

Conditional statements allow you to execute different code blocks based on different conditions. Python uses if, elif, and else statements for conditional execution.

Conditional Statements:

  • if - Execute if condition is True
  • elif - Execute if previous conditions are False and this condition is True
  • else - Execute if all previous conditions are False

Comparison Operators:

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

Logical Operators:

  • and - Both conditions must be True
  • or - At least one condition must be True
  • not - Reverse the result

Hands-on Examples

If-Else Statements

# Basic if statement
age = 18
if age >= 18:
    print("You are an adult")

# If-else statement
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Score: {score}, Grade: {grade}")

# Multiple conditions
temperature = 25
humidity = 60

if temperature > 30 and humidity > 70:
    print("Hot and humid day")
elif temperature > 30 or humidity > 70:
    print("Either hot or humid")
else:
    print("Pleasant weather")

# Nested conditions
user_type = "premium"
purchase_amount = 150

if user_type == "premium":
    if purchase_amount > 100:
        discount = 0.2
    else:
        discount = 0.1
else:
    discount = 0.05

print(f"Discount: {discount * 100}%")

Conditional statements help control the flow of your program based on different conditions.