Interaktive Programme und Wiederholungen
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}!")
# 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.")
→ kapitel_7_aufgaben_7-1_7-3.ipynb
↓ Lösungen
# 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.")
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.
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)
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)
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!
→ kapitel_7_aufgaben_7-4_7-7.ipynb
↓ Lösungen
# 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.")
# 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.")
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
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
# 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}")
# 3. break-Anweisung
while True:
topping = input("Enter a topping (or 'quit'): ")
if topping == 'quit':
break
print(f"Adding {topping}")
# 7-7: Endlosschleife
while True:
print("This will run forever! Press Ctrl+C to stop.")
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
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)
# 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())
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}.")
→ kapitel_7_aufgaben_7-8_7-10.ipynb
↓ Lösungen
# 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)
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.
# 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()}.")
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.
# 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)