While-Schleifen werden so lange wiederholt, wie eine bestimmte boolesche Bedingung erfüllt ist.
# Denke daran, 'count' zu inkrementieren, sonst wird die Schleife ewig fortgesetzt
zähler = 0
while zähler < 5:
print(zähler)
zähler += 1
Die break-Anweisung
Die Anweisung break
kann die Schleife beenden, auch wenn die while-Bedingung wahr ist.
i = 1
while i < 10:
print(i)
if i == 3:
break
i += 1
Die continue-Anweisung
Die Anweisung continue
kann die aktuelle Iteration anhalten und mit der nächsten fortfahren.
i = 1
while i < 10:
i += 1
if i == 3:
continue
print(i)
Die else-Anweisung
Die else
-Anweisung kann einen Codeblock einmalig ausführen, wenn die Bedingung nicht mehr wahr ist.
i = 1
while i < 5:
print(i)
i += 1
else:
print("i ist nicht mehr kleiner als 5")
Übung
Ändere den Code mit Hilfe der while-Schleife so ab, dass x so lange gedruckt wird, wie x kleiner als 9 ist, aber die Zahl 5 nicht gedruckt wird.
x = 1
while x < 5:
print(x)
x += 1
x = 1
while x < 9:
if x == 5:
continue
print(x)
x += 1
test_object('x', incorrect_msg="Vergiss nicht, die Anleitung zu lesen.")
test_output_contains("1")
test_output_contains("2")
test_output_contains("3")
test_output_contains("4")
test_output_contains("6")
test_output_contains("7")
test_output_contains("8")
test_output_contains("9")
success_msg("Hervorragend!")