Python Lesson 8: Conditions (if/elif/else)

🐍 Python CourseLesson 8 of 26 · 31% complete

Programs make decisions. Conditions let your code run different blocks based on whether something is True or False. This is where programs become smart.

Basic if Statement

age = 20

if age >= 18:
    print("You are an adult")
    print("You can vote")

# Indentation (4 spaces) is required!
# Python uses indentation instead of curly braces

if / else

password = input("Enter password: ")

if password == "secret123":
    print("Access granted!")
else:
    print("Wrong password. Try again.")

if / elif / else

score = int(input("Enter your test score (0-100): "))

if score >= 90:
    print(f"Score: {score} -- Grade A -- Excellent!")
elif score >= 80:
    print(f"Score: {score} -- Grade B -- Good job!")
elif score >= 70:
    print(f"Score: {score} -- Grade C -- Keep studying!")
elif score >= 60:
    print(f"Score: {score} -- Grade D -- Need improvement")
else:
    print(f"Score: {score} -- Grade F -- Please retake")

Nested Conditions

age = 22
has_ticket = True

if age >= 18:
    if has_ticket:
        print("Welcome to the concert!")
    else:
        print("You need a ticket first")
else:
    print("Sorry, 18+ only")

Common Mistake: = vs ==

x = 5          # assignment — stores 5
if x == 5:     # comparison — asks "is x equal to 5?"
    print("yes")

# NEVER write: if x = 5:  -- SyntaxError!

🏋️ Practice Task

Build a number guessing game (no loops yet). Set secret_number = 7. Ask user to guess. Print “Too high!”, “Too low!”, or “Correct! You got it!” based on their guess.

💡 Hint: Use int(input()) to get the guess. Compare with == < > in if/elif/else blocks.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *