Alles Wichtige aus den ersten 8 Kapiteln
print("Hello, World!")
print("Hello Python world!")
# Das war unser erstes Programm!
name = "Ada Lovelace"
message = f"Hello, {name}!"
print(message.upper())
print(message.lower())
print(message.title())
age = 23
temperature = 17.5
# Rechnen
result = 2 + 3 * 4
print(2 ** 3) # 8
print(17 / 5) # 3.4
print(17 // 5) # 3
# Liste erstellen
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
# Zugriff auf Elemente
print(bicycles[0]) # 'trek'
print(bicycles[-1]) # 'specialized'
# Listen ändern
bicycles[0] = 'giant'
bicycles.append('scott')
bicycles.insert(1, 'cube')
bicycles.remove('redline')
print(len(bicycles)) # Anzahl Elemente
# for-Schleife
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"{magician.title()}, I can't wait to see your next trick!")
print("Thank you, everyone. That was a great magic show!")
# range() verwenden
for value in range(1, 5):
print(value) # 1, 2, 3, 4
# Listen mit range()
numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]
even_numbers = list(range(2, 11, 2)) # [2, 4, 6, 8, 10]
# List Comprehensions
squares = [value**2 for value in range(1, 11)]
print(squares[:5]) # [1, 4, 9, 16, 25]
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
# Statistische Funktionen
print(f"Minimum: {min(digits)}") # 0
print(f"Maximum: {max(digits)}") # 9
print(f"Summe: {sum(digits)}") # 45
print(f"Anzahl: {len(digits)}") # 10
# Noch mehr Statistiken
print(f"Durchschnitt: {sum(digits)/len(digits):.1f}") # 4.5
players = ['charles', 'martina', 'michael', 'florence', 'eli']
# Slicing
print(players[0:3]) # ['charles', 'martina', 'michael']
print(players[1:4]) # ['martina', 'michael', 'florence']
print(players[:4]) # Erste 4
print(players[2:]) # Ab Index 2
print(players[-3:]) # Letzte 3
# Kopien von Listen
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] # Kopie!
# nicht: friend_foods = my_foods # Das wäre nur eine Referenz
age = 19
# Einfache if-Anweisung
if age >= 18:
print("You are old enough to vote!")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
# Mehrere Bedingungen
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print(f"Your admission cost is ${price}.")
requested_toppings = ['mushrooms', 'extra cheese']
# Einzelne Werte prüfen
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
# Gleichheit und Ungleichheit
print(5 == 5) # True
print(5 != 3) # True
# Größer/kleiner
print(5 > 3) # True
print(5 < 3) # False
print(5 >= 5) # True
print(4 <= 3) # False
age_0 = 22
age_1 = 18
# and: beide Bedingungen müssen True sein
print(age_0 >= 21 and age_1 >= 21) # False
# or: eine Bedingung muss True sein
print(age_0 >= 21 or age_1 >= 21) # True
# not: kehrt Boolean-Wert um
print(not age_0 < 18) # True
# Listen testen
users = ['admin', 'guest', 'user']
print('admin' in users) # True
print('root' in users) # False
print('root' not in users) # True
# Mit Strings
word = "hello"
print('e' in word) # True
print('x' not in word) # True
# Boolean Werte
game_active = True
can_edit = False
# Dictionary erstellen
alien_0 = {'color': 'green', 'points': 5}
# Werte abrufen
print(alien_0['color'])
print(alien_0.get('color'))
print(alien_0.get('speed', 'No speed value assigned'))
# Hinzufügen und Ändern
alien_0['x_position'] = 0
alien_0['y_position'] = 25
alien_0['speed'] = 'medium'
print(alien_0)
# Werte löschen
del alien_0['points']
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
# Durch Schlüssel-Wert-Paare iterieren
for key, value in user_0.items():
print(f"Key: {key}")
print(f"Value: {value}")
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
# Nur Schlüssel
print("Schlüssel:")
for key in user_0.keys():
print(f"- {key}")
# Nur Werte
print("\nWerte:")
for value in user_0.values():
print(f"- {value.title()}")
# Liste von Dictionaries
users = [
{'username': 'efermi', 'first': 'enrico', 'last': 'fermi'},
{'username': 'mcurie', 'first': 'marie', 'last': 'curie'}
]
# Durch verschachtelte Struktur iterieren
for user in users:
print(f"\nBenutzer: {user['username']}")
print(f"Name: {user['first'].title()} {user['last'].title()}")
# input() Funktion
name = input("Please enter your name: ")
print(f"Hello, {name}!")
# Zahlen eingeben (wichtig: int() verwenden!)
age = int(input("How old are you? "))
if age >= 18:
print("You can vote!")
else:
print(f"In {18-age} years you can vote!")
# Einfache while-Schleife
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
# Countdown
countdown = 10
while countdown > 0:
print(f"Countdown: {countdown}")
countdown -= 1
print("Start!")
# Mit break
while True:
message = input("\nEnter a message (or 'quit'): ")
if message == 'quit':
break
print(f"You said: {message}")
# Mit continue
counter = 0
while counter < 10:
counter += 1
if counter % 2 == 0: # Gerade Zahlen überspringen
continue
print(f"Ungerade Zahl: {counter}")
# 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(f"Confirmed users: {confirmed_users}")
# Alle Vorkommen eines Wertes entfernen
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(f"Vorher: {pets}")
while 'cat' in pets:
pets.remove('cat')
print(f"Nachher: {pets}")
# Ausgabe: ['dog', 'dog', 'goldfish', 'rabbit']
# Dictionary mit while füllen
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat == 'no':
polling_active = False
# Ergebnisse anzeigen
print("\n--- Poll Results ---")
for name, mountain in responses.items():
print(f"{name} would like to climb {mountain}.")
→ recap_aufgaben_1.ipynb
↓ Lösungen
# R1-R5: Liebingsfilme
movies = ['The Matrix', 'Star Wars', 'Inception', 'Avengers', 'Interstellar']
# R2: Mit for-Schleife ausgeben
print("Meine Liebingsfilme:")
for movie in movies:
print(f"- {movie}")
# R3: Zweiten Film ändern
movies[1] = 'Empire Strikes Back'
print(f"\nGeändert: {movies}")
# R4: Neuen Film hinzufügen
movies.append('Dune')
print(f"Mit neuem Film: {movies}")
# R5: Erste 3 Filme
print(f"Top 3: {movies[:3]}")
Meine Liebingsfilme:
- The Matrix
- Star Wars
- Inception
- Avengers
- Interstellar
Geändert: ['The Matrix', 'Empire Strikes Back', 'Inception', 'Avengers', 'Interstellar']
Mit neuem Film: ['The Matrix', 'Empire Strikes Back', 'Inception', 'Avengers', 'Interstellar', 'Dune']
Top 3: ['The Matrix', 'Empire Strikes Back', 'Inception']
→ recap_aufgaben_2.ipynb
↓ Lösungen
# R6: Schüler-Dictionary
student = {
'name': 'Max Mustermann',
'age': 17,
'class': '11a'
}
# R7: Alter überprüfen
if student['age'] > 16:
print(f"{student['name']} ist über 16 Jahre alt.")
else:
print(f"{student['name']} ist 16 oder jünger.")
# R8: Liste mit mehreren Schülern
students = [
{'name': 'Max Mustermann', 'age': 17, 'class': '11a'},
{'name': 'Anna Schmidt', 'age': 15, 'class': '10b'},
{'name': 'Tom Weber', 'age': 18, 'class': '12c'}
]
# R9 & R10: Schüler durchlaufen und zählen
older_than_16 = 0
print("Schülerinfo:")
for student in students:
print(f"{student['name']}: {student['age']} Jahre, Klasse {student['class']}")
if student['age'] > 16:
older_than_16 += 1
print(" → Über 16 Jahre alt")
print(f"\nAnzahl Schüler über 16: {older_than_16}")
Max Mustermann ist über 16 Jahre alt.
Schülerinfo:
Max Mustermann: 17 Jahre, Klasse 11a
→ Über 16 Jahre alt
Anna Schmidt: 15 Jahre, Klasse 10b
Tom Weber: 18 Jahre, Klasse 12c
→ Über 16 Jahre alt
Anzahl Schüler über 16: 2
→ recap_aufgaben_3.ipynb
↓ Lösungen
import random
# R11: Zufallszahl generieren & Spiel starten
secret_number = random.randint(1, 10)
attempts = 0
print("🎲 Ich denke mir eine Zahl zwischen 1 und 10!")
print("Kannst du sie erraten?")
# R12-R14: Rate-Schleife mit Hinweisen und Zähler
while True:
try:
guess = int(input("Dein Tipp: "))
attempts += 1
if guess == secret_number:
print(f"🎉 Richtig! Du hast {attempts} Versuche gebraucht.")
break
elif guess < secret_number:
print("📈 Zu niedrig!")
else:
print("📉 Zu hoch!")
except ValueError:
print("Bitte gib eine gültige Zahl ein!")
# R15: "Nochmal spielen?"-Funktionalität
play_again = True
while play_again:
secret_number = random.randint(1, 10)
attempts = 0
print("\n🎲 Neue Runde! Ich denke mir eine Zahl zwischen 1 und 10!")
# [Rate-Schleife von vorheriger Slide hier einfügen]
answer = input("\n🔄 Nochmal spielen? (ja/nein): ").lower()
play_again = answer in ['ja', 'j', 'yes', 'y']
print("Danke fürs Spielen! 👋")
🎲 Neue Runde! Ich denke mir eine Zahl zwischen 1 und 10!
Dein Tipp: 5
📉 Zu hoch!
Dein Tipp: 3
📈 Zu niedrig!
Dein Tipp: 4
🎉 Richtig! Du hast 3 Versuche gebraucht.
🔄 Nochmal spielen? (ja/nein): nein
Danke fürs Spielen! 👋
print "Hello" → print("Hello")if x = 5: → if x == 5:age = input("Age: ") → age = int(input("Age: "))my_list[len(my_list)] → my_list[-1]student_name statt snWas erwartet uns?
def greet_user(name, greeting="Hello"):
"""Greet a user with a personalized message."""
return f"{greeting}, {name}!"
message = greet_user("Alice", "Hi")
print(message) # "Hi, Alice!"
🚀 Bereit für Funktionen? Let's go! 🚀