Question: In Python, there are break and continue statements. The break statement takes the code out of a loop. A continue statement does not execute the
In Python, there are break and continue statements. The break statement takes the code out of a loop. A continue statement does not execute the hcode after this statement and goes to the start of the loop.
You need to be careful and still update the conditional variable in the while loop.
What if you had nested loops, say 2 while loops. Where would the break statements take you in the following code?
x = 0
y = 10
while(x < 10):
x += 1
print('x = ' + str(x))
while(y > x):
y -= 1
if y == 4:
print('y == 4')
break;
print('y = %d' % y)
y -= 1
if(x == 6):
break
With output:
x = 1
y == 4
y = 4
x = 2
y = 2
x = 3
y = 1
x = 4
y = 0
x = 5
y = -1
x = 6
y = -2
How could you rewrite this while loop into a for loop? What advantage would a for loop have?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
