DE EN

Conditions

if, elif, else — how your program makes decisions and controls the flow of code.

50 Min Mittel

Lernziele dieses Kapitels

  • You build if-elif-else structures for decision trees
  • You understand nested conditions and when they make sense
  • You use Truthy and Falsy in Python for elegant checks
  • You expand PyBuddy with a mood check

if, elif, else

Conditions control the program flow. In Python indentation (4 spaces) is mandatory — it replaces the curly braces from JavaScript.

The flow is always: if checks the first condition, elif (else if) checks alternatives, else catches all remaining cases.

Warning

Don't forget the colon : at the end of every condition! Otherwise Python throws a SyntaxError.

Python
# Grade calculator with if-elif-else
prozent = float(input("Percentage: "))

if prozent >= 89:
    note = 1
elif prozent >= 76:
    note = 2
elif prozent >= 63:
    note = 3
elif prozent >= 50:
    note = 4
else:
    note = 5

print(f"Your grade: {note}")
Ausgabe
Percentage: 82 Your grade: 2
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
if prozent >= 89:
    note = 1
elif prozent >= 76:
    note = 2
else:
    note = 3
JavaScript
if (prozent >= 89) {
    note = 1;
} else if (prozent >= 76) {
    note = 2;
} else {
    note = 3;
}
Merke: Python uses indentation and : instead of curly braces. elif in Python is else if in JavaScript. The logic is identical!

Nested Conditions

Conditions inside conditions enable complex logic. Imagine you first check whether a player is online, and then whether they have enough mana for a spell.

But be careful: Beyond 3 nesting levels code quickly becomes unreadable. Then functions (Chapter 8) are the better choice.

Python
# Nested conditions: Login system
name = input("Username: ")
passwort = input("Password: ")

if name == "admin":
    if passwort == "geheim123":
        print(" Login successful!")
    else:
        print(" Wrong password.")
else:
    print(" User not found.")

# More compact with and:
if name == "admin" and passwort == "geheim123":
    print(" Login successful!")
else:
    print(" Access denied.")
Ausgabe
Username: admin Password: geheim123 Login successful!

Truthy & Falsy

In Python certain values are automatically considered False — this is called Falsy. All other values are Truthy (i.e. True).

  • Falsy: 0, 0.0, "" (empty string), [] (empty list), None, {}
  • Truthy: Everything else, e.g. "Hello", 42, [1, 2]

This enables very elegant checks.

Python
# Truthy & Falsy in Python
name = input("Your name: ")

# Elegant instead of name != "":
if name:
    print(f"Hello {name}!")
else:
    print("You entered nothing.")

# Also with lists
aufgaben = []
if not aufgaben:
    print("No tasks available.")

aufgaben = ["Python lernen"]
if aufgaben:
    print(f"You have {len(aufgaben)} task(s).")
Ausgabe
Your name: Max Hello Max! No tasks available. You have 1 task(s).
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
if name:
    print("Hello!")
if not aufgaben:
    print("Empty")
JavaScript
if (name) {
    console.log("Hello!");
}
if (!aufgaben.length) {
    console.log("Empty");
}
Merke: In Python you check directly if name: or if not aufgaben:. In JavaScript you need .length for arrays and empty strings are also falsy — but empty arrays are truthy!

match-case for Pattern Matching

From Python 3.10 onwards there is match-case — an elegant replacement for long if-elif chains when you check a value against multiple patterns. It is comparable to switch-case in other languages, but much more powerful.

Python
# match-case instead of if-elif
befehl = input("Command: ").lower()

match befehl:
    case "hello":
        print(" Hello!")
    case "help":
        print(" Available commands: hello, status, exit")
    case "status":
        print(" PyBuddy is online.")
    case "exit":
        print(" Bye!")
    case _:
        print(" Unknown command.")
Ausgabe
Command: status PyBuddy is online.

Conditions in Action: Quest Status

Imagine an RPG where the player must complete a quest. You need to check: Does he have the item? Is his level high enough? Does he have enough time?

Python
# Quest check in an RPG
level = 12
item = "Dragon scale"
zeit = 45  # minutes

if level >= 10 and item == "Dragon scale" and zeit <= 60:
    print(" Quest completed!")
    print(" Reward: 500 XP + Legendary Sword")
elif level < 10:
    print("⛔ Your level is too low. Required: Level 10")
elif item != "Dragon scale":
    print("⛔ You are missing the required item.")
else:
    print(" Time expired!")
Ausgabe
Quest completed! Reward: 500 XP + Legendary Sword

Warm-Up: Grade Calculator

Write a program that reads a percentage and outputs the school grade (1-5). Use if-elif-else.

Hinweis: p = float(input("Percent: ")) if p >= 89: n = 1 elif p >= 76: n = 2 elif p >= 63: n = 3 elif p >= 50: n = 4 else: n = 5 print(f"Grade: {n}")

Solution
p = float(input("Percent: "))
if p >= 89: n = 1
elif p >= 76: n = 2
elif p >= 63: n = 3
elif p >= 50: n = 4
else: n = 5
print(f"Grade: {n}")

Challenge: Password Strength Checker

Check a password for strength: at least 8 characters, contains a number, contains an uppercase letter. Use nested conditions and len().

Hinweis: pw = input("Password: ") has_digit = any(c.isdigit() for c in pw) has_upper = any(c.isupper() for c in pw) if len(pw) < 8: print(" Too short") elif not has_digit: print(" No number") elif not has_upper: print(" No uppercase letter") else: print(" Strong!")

Solution
pw = input("Password: ")
has_digit = any(c.isdigit() for c in pw)
has_upper = any(c.isupper() for c in pw)

if len(pw) < 8:
    print(" Too short")
elif not has_digit:
    print(" No number")
elif not has_upper:
    print(" No uppercase letter")
else:
    print(" Strong!")

PyBuddy Checkpoint: Mood Check

PyBuddy asks for the mood (1-5) and outputs appropriate responses. Use if-elif-else and f-Strings.

Hinweis: # pybuddy/main.py stimmung = int(input(" How is your mood (1-5)? ")) if stimmung >= 4: print(" Great! Let's be productive!") elif stimmung == 3: print(" Good! A good day for learning.") elif stimmung >= 1: print(" No problem. Every day is different.") else: print(" Please enter a number between 1 and 5.")

Solution
# pybuddy/main.py
stimmung = int(input(" How is your mood (1-5)? "))

if stimmung >= 4:
    print(" Great! Let's be productive!")
elif stimmung == 3:
    print(" Good! A good day for learning.")
elif stimmung >= 1:
    print(" No problem. Every day is different.")
else:
    print(" Please enter a number between 1 and 5.")
Learning Break

In Undertale the complete game behavior changes based on if-else decisions: Do you kill enemies or spare them? The game saves your decision in a variable and checks it with conditions — exactly what you can do now!

Zusammenfassung

  • if → elif → else for decision trees
  • Nesting possible, but max. 2-3 levels
  • Truthy/Falsy: empty, 0, None = automatically False
  • match-case (Python 3.10+) for pattern matching
  • Conditions control the entire program flow