Python Crash Course

Kapitel 7

Benutzereingaben und while-Schleifen

Interaktive Programme und Wiederholungen

Die input()-Funktion

  • Fordert Benutzer zur Eingabe auf
  • Gibt immer einen String zurück
  • Programm pausiert bis zur Eingabe
message = input("Tell me something, and I will repeat it back to you: ")
print(message)

# Mit Prompt-Variable für bessere Lesbarkeit
prompt = "If you tell us who you are, we can personalize the messages."
prompt += "\nWhat is your first name? "

name = input(prompt)
print(f"\nHello, {name}!")

Numerische Eingaben

# input() gibt immer String zurück
age = input("How old are you? ")
print(type(age))  # 

# Umwandlung in Integer
age = int(input("How old are you? "))
print(type(age))  # 

# Modulo-Operator für gerade/ungerade
number = int(input("Enter a number: "))
if number % 2 == 0:
    print(f"\nThe number {number} is even.")
else:
    print(f"\nThe number {number} is odd.")

🛠️ Übung 1: Benutzereingaben

🔗 jupyter.gymnasium-hummelsbuettel.de

Aufgaben 7-1 bis 7-3:

  • 7-1: Leihwagen - Autoart abfragen
  • 7-2: Restaurantplätze - Personenzahl prüfen
  • 7-3: Vielfache von 10 erkennen

→ kapitel_7_aufgaben_7-1_7-3.ipynb

↓ Lösungen

💡 Lösungen Übung 1

# 7-1: Leihwagen
car = input("What kind of rental car would you like? ")
print(f"Let me see if I can find you a {car}.")

# 7-2: Restaurantplätze
party_size = int(input("How many people are in your dinner group? "))

if party_size > 8:
    print("You'll have to wait for a table.")
else:
    print("Your table is ready.")

# 7-3: Vielfache von 10
number = int(input("Enter a number: "))

if number % 10 == 0:
    print(f"{number} is a multiple of 10.")
else:
    print(f"{number} is not a multiple of 10.")

📄 Ausgabe - Übung 1

What kind of rental car would you like? SUV
Let me see if I can find you a SUV.
How many people are in your dinner group? 6
Your table is ready.
Enter a number: 20
20 is a multiple of 10.

while-Schleifen

Wiederholen Code solange eine Bedingung True ist

current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1

# Benutzer-gesteuerte Schleife
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

message = ""
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print(message)

Flaggen-Variable

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

active = True
while active:
    message = input(prompt)
    
    if message == 'quit':
        active = False
    else:
        print(message)

# break-Anweisung
while True:
    message = input(prompt)
    
    if message == 'quit':
        break
    else:
        print(message)

continue-Anweisung

current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    
    print(current_number)

# Ausgabe: 1, 3, 5, 7, 9

# Endlosschleifen vermeiden
x = 1
while x <= 5:
    print(x)
    x += 1  # Wichtig: Zähler erhöhen!

🛠️ Übung 2: while-Schleifen

Aufgaben 7-4 bis 7-7:

  • 7-4: Pizzabeläge eingeben
  • 7-5: Eintrittskarten - Altersabhängig
  • 7-6: Drei Arten der Beendigung
  • 7-7: Endlosschleife (Strg+C)

→ kapitel_7_aufgaben_7-4_7-7.ipynb

↓ Lösungen

💡 Lösung 7-4

# 7-4: Pizzabeläge
prompt = "\nWhich topping would you like on your pizza?"
prompt += "\nEnter 'quit' when you are finished: "

while True:
    topping = input(prompt)
    
    if topping == 'quit':
        break
    else:
        print(f"I'll add {topping} to your pizza.")

💡 Lösung 7-5

# 7-5: Eintrittskarten
prompt = "\nHow old are you?"
prompt += "\nEnter 'quit' when you are finished: "

while True:
    age = input(prompt)
    
    if age == 'quit':
        break
    
    age = int(age)
    
    if age < 3:
        print("Your ticket is free.")
    elif age < 12:
        print("Your ticket is $10.")
    else:
        print("Your ticket is $15.")

📄 Ausgabe 7-4

Which topping would you like on your pizza?
Enter 'quit' when you are finished: mushrooms
I'll add mushrooms to your pizza.

Which topping would you like on your pizza?
Enter 'quit' when you are finished: pepperoni
I'll add pepperoni to your pizza.

Which topping would you like on your pizza?
Enter 'quit' when you are finished: quit

📄 Ausgabe 7-5

How old are you?
Enter 'quit' when you are finished: 25
Your ticket is $15.

How old are you?
Enter 'quit' when you are finished: 8
Your ticket is $10.

How old are you?
Enter 'quit' when you are finished: quit

💡 Lösung 7-6 (Teil 1)

# 7-6: Drei Arten der Beendigung

# 1. Bedingung in while-Anweisung
topping = ""
while topping != 'quit':
    topping = input("Enter a topping (or 'quit'): ")
    if topping != 'quit':
        print(f"Adding {topping}")

# 2. Flagvariable
active = True
while active:
    topping = input("Enter a topping (or 'quit'): ")
    if topping == 'quit':
        active = False
    else:
        print(f"Adding {topping}")

💡 Lösung 7-6 (Teil 2)

# 3. break-Anweisung
while True:
    topping = input("Enter a topping (or 'quit'): ")
    if topping == 'quit':
        break
    print(f"Adding {topping}")

💡 Lösung 7-7

# 7-7: Endlosschleife
while True:
    print("This will run forever! Press Ctrl+C to stop.")

📄 Ausgabe 7-6

Enter a topping (or 'quit'): cheese
Adding cheese
Enter a topping (or 'quit'): quit
Enter a topping (or 'quit'): olives
Adding olives
Enter a topping (or 'quit'): quit
Enter a topping (or 'quit'): tomatoes
Adding tomatoes
Enter a topping (or 'quit'): quit

📄 Ausgabe 7-7

This will run forever! Press Ctrl+C to stop.
This will run forever! Press Ctrl+C to stop.
This will run forever! Press Ctrl+C to stop.
... (continues until stopped)

while-Schleifen mit Listen

# Elemente zwischen Listen verschieben
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    
    print(f"Verifying user: {current_user.title()}")
    confirmed_users.append(current_user)

print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

Alle Vorkommen eines Wertes entfernen

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')

print(pets)

# Dictionary mit Benutzereingaben füllen
responses = {}

polling_active = True

while polling_active:
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")
    
    responses[name] = response
    
    repeat = input("Would you like to let another person respond? (yes/ no) ")
    if repeat == 'no':
        polling_active = False

print("\n--- Poll Results ---")
for name, response in responses.items():
    print(f"{name} would like to climb {response}.")

🛠️ Übung 3: Listen und while

Aufgaben 7-8 bis 7-10:

  • 7-8: Sandwiches - Listen verschieben
  • 7-9: Kein Pastrami - Elemente entfernen
  • 7-10: Traumurlaub - Dictionary füllen

→ kapitel_7_aufgaben_7-8_7-10.ipynb

↓ Lösungen

💡 Lösungen Übung 3 (Teil 1)

# 7-8: Sandwiches
sandwich_orders = ['tuna', 'ham', 'turkey', 'veggie', 'club']
finished_sandwiches = []

while sandwich_orders:
    current_sandwich = sandwich_orders.pop()
    print(f"I made your {current_sandwich} sandwich.")
    finished_sandwiches.append(current_sandwich)

print("\nAll sandwiches made:")
for sandwich in finished_sandwiches:
    print(f"- {sandwich.title()}")

# 7-9: Kein Pastrami
sandwich_orders = ['pastrami', 'tuna', 'pastrami', 'ham', 'pastrami', 'turkey']
finished_sandwiches = []

print("The deli has run out of pastrami.")

while 'pastrami' in sandwich_orders:
    sandwich_orders.remove('pastrami')

while sandwich_orders:
    current_sandwich = sandwich_orders.pop()
    print(f"I made your {current_sandwich} sandwich.")
    finished_sandwiches.append(current_sandwich)

📄 Ausgabe - Übung 3 Teil 1

I made your club sandwich.
I made your veggie sandwich.
I made your turkey sandwich.
I made your ham sandwich.
I made your tuna sandwich.

All sandwiches made:
- Club
- Veggie
- Turkey
- Ham
- Tuna
The deli has run out of pastrami.
I made your turkey sandwich.
I made your ham sandwich.
I made your tuna sandwich.

💡 Lösungen Übung 3 (Teil 2)

# 7-10: Traumurlaub
responses = {}

while True:
    name = input("\nWhat is your name? ")
    place = input("If you could visit one place in the world, where would you go? ")
    
    responses[name] = place
    
    repeat = input("Would you like to let another person respond? (yes/no) ")
    if repeat == 'no':
        break

print("\n--- Dream Vacation Poll Results ---")
for name, place in responses.items():
    print(f"{name.title()} would like to visit {place.title()}.")

📄 Ausgabe - Übung 3 Teil 2

What is your name? Alice
If you could visit one place in the world, where would you go? Japan
Would you like to let another person respond? (yes/no) yes

What is your name? Bob
If you could visit one place in the world, where would you go? Italy
Would you like to let another person respond? (yes/no) no

--- Dream Vacation Poll Results ---
Alice would like to visit Japan.
Bob would like to visit Italy.

Zusammenfassung Kapitel 7

  • input(): Benutzereingaben erfassen
  • int(): String zu Integer konvertieren
  • while: Bedingte Wiederholung
  • Flags: Boolean-Variablen zur Steuerung
  • break/continue: Schleifenkontrolle
  • Listen: Elemente verschieben und entfernen

Praktische Tipps

  • Eingabe-Validierung: Immer auf korrekte Datentypen prüfen
  • Endlosschleifen: Immer Ausstiegsmöglichkeit vorsehen
  • Flags: Bei komplexen Bedingungen verwenden
  • Benutzerfreundlichkeit: Klare Anweisungen geben
# Gut - mit Validierung
try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Please enter a valid number.")

# Gut - klarer Prompt
prompt = "Enter 'quit' to exit or any other text to continue: "
message = input(prompt)