Flow Control#
Für mehr Kontrolle in For- und While-Schleifen sorgen die folgenden Anweisungen:
break - bricht eine Schleife frühzeitig ab
continue - überspringt die aktuelle Iteration. Der Rest der Schleife wird jedoch weiter ausgeführt
pass - ignoriert eine Bedingung und führt die Schleife weiter aus
# Normale Schleife
print('Start Loop\n')
for number in range(10):
print('Number is ' + str(number))
print('\n End Loop')
Start Loop
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
End Loop
# Break
print('Start Loop\n')
for number in range(10):
if number == 5:
break
print('Number is ' + str(number))
print('\n End Loop')
Start Loop
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
End Loop
# Continue
print('Start Loop\n')
for number in range(10):
if number == 5:
continue
print('Number is ' + str(number))
print('\n End Loop')
Start Loop
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 6
Number is 7
Number is 8
Number is 9
End Loop
# Pass
print('Start Loop\n')
for number in range(10):
if number == 5:
pass
print('Number is ' + str(number))
print('\n End Loop')
Start Loop
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
End Loop
Pass#
pass
wird häufig auch als Platzhalter eingefügt wenn beispielweise Funktionen noch nicht implementiert sind.
def my_function():
pass
my_function()