Prev: - 'if' control | Next: 'for' loop
A typical use of 'break' is to call it and exit a loop when a condition is True. In its general form this code might be as follows:
while condition-1:
block-1
if condition-2:
break
else:
block-2
In the above example when condition-2 is True the 'break' command transfers the flow outside the 'while' command (the 'else' branch is NOT executed in this case)
Although break carries a bit of 'go to' taste, however it fits well to structured programming as it tranfers the flow specifically to the end of the loop and nowhere else.
# 'break' exits the endless while loop when i equals x
x = int(input('Enter an integer in [1,10]:'))
asum = i = 0
while True:
i += 1
asum += i
if i == x:
break
print(asum)
In its general form this code might be as follows:
while condition-1:
block-1
if condition-2:
continue
block-2
else:
block-else
In the above example code when condition-2 is True the 'continue' command transfers the flow to the beginning of the 'while' loop: the 'block-2' code is NOT executed in this case
# calculating sums of integers
num = int(input('Please enter an integer number in [1,100]:'))
totsum = oddsum = i = 0
while True:
i += 1
if i > num: break
totsum += i
if i%2 == 0: continue
oddsum += i
print('Max number added:',i-1,
'Sum of all numbers:',totsum,
'Sum of odd numbers:',oddsum)
# 'pass' your code!
key = -2
if key > 0:
print('key is positive!')
else:
pass # I don't know what the 'else' branch will finally do but the code runs smoothly
. Free learning material
. See full copyright and disclaimer notice