Break out of Python for loop - python

I was wondering if there's a way I can have my for loop print out the statement right after the 5th loop instead of calling it 6 times and stopping at 5 using my if statement.
Is there a more efficient way to accomplish this? Thanks.
for counter in range (6):
if counter == 5:
print("Maximum speed reached!\n")
break ##Break out of loop if condition met.
myCar.accelerate()
time.sleep(1) ##Add 1 second delay each loop.

You could just iterate until 5 instead of 6 and print your message out of the loop:
for counter in range(5):
# Remove the if statement:
# if counter == 5:
# print("")
# break
myCar.accelerate()
time.sleep(1)
print("Maximum speed reached!")

Related

It is possible to not increment count in for loop - Python

it is possible to not increment count in for loop in case an error happen, like this example
for i in range(10):
try:
print(i)
except: # if and error happen in i == 5 the next iteration will be 5 not 6
pass
I want to repeat the same iteration when the error happen. And thanks in advance.
When you use for...in there's no way to avoid going to the next item in the iteration when the loop repeats.
You can use a nested loop to keep trying with the same value of i until you don't get an error:
for i in range(10):
while True:
try:
print(i)
break
except:
pass
Maybe wrap all into a while loop:
for i in range(10):
while True
try:
# whatever you have to do
print(i)
break
except:
pass
Since Python's for loop is technically a foreach loop you should use a while instead of for for more control.
i = 0
while i<10:
try:
#Do stuf
i += 1
except:
pass
If an error happens before i += 1 it will not be incremented.

It should have been an infinite loop

I wrote a code in python. While changing the code, I asked myself what should be the output.
I also answered myself it should be an infinite loop. Then I ran it. But surprisingly it wasn't an infinite loop. My question is why ?
i=0
for i in range(10):
if i == 5:
i -=1
else:
print(i)
i+=1
It's very basic in python. For your information, the range() function generates a list. Here range(5) means [0,1,2,3,4].
So i iterates through the list [0,1,2,3,4] one by one. i doesn't hold the same value initialized from the beginning like a while loop condition.
for i in [0,1,2,3,4]:
if i==5:
i-=1
else:
print(i)
i+=1
Your code and this code perform similarly. The next value of i doesn't depend on the previous value of i but on the objects of the list.
Further study might be helpful for you.
range(10) produces the sequence 0,1,...,9 from which your i variable takes its values in the loop. The fact that you do i -= 1 when i == 5 won't make i to switch back and forth from 5 to 4 on and on because i is taking its values from range(10). What happens when i == 5 is that it becomes i == 4 when you do i -= 1 but at the next iteration i will take the next value from the range which would be 6, and so on until the loop ends.
Here's an infinite loop:
i=0
while i < 10:
if i == 5:
i -=1
else:
print(i)
i+=1

Why is the break statement in the code not working (python)

this is code to print the lowest positive integer present in a list.
break statement is not working and the loop is running infinitely.
list = []
n=1
print("enter array")
for i in range (5) :
a=(int(input()))
list.append(a)
while n<4 :
for i in range (5) :
if(list[i]== n):
n=n+1
continue
else:
print("the number should be" , n)
break
the break statement refers to the inner most loop level
the code below is an infinite loop:
while True:
for i in range(10):
if i == 5:
break # breaks the for, start a new iteration of the while loop
To break the while loop, you may consider using some kind of flag like this
while True:
broken = False
for i in xrange(10):
if i == 5:
broken = True
# break the for loop
break
if broken:
# break the while loop
break
the for-else statement may also be helpful here:
while True:
for ...:
if ...:
# break the for loop
break # refers to the for statement
else:
# the breaking condition was never met during the for loop
continue # refers to the while statement
# this part only execute if the for loop was broken
break # refers to the while statement

What does the continue statement do?

Can someone explain why this causes an infinite loop even tho the continue from what I have been reading should "skip" the iteration
x = 0
while x < 50:
if x == 33:
print("I hit 33")
continue
else:
pass
print(x)
x+=1
The continue command restarts the innermost loop at the condition.
That means after x reaches 33, x += 1 will never execute because you will be hitting the continue and going back to the while line without running the rest of the code block.
x will forever be 33 so you will have a infinite loop.
You are skipping the increment that happens at the end of the while loop when you call continue. The following will automatically increment if you want to keep the continue statement:
for x in range(50):
if x == 33:
print("I hit 33")
continue
else:
print(x)
Otherwise, delete the continue.
I think you are confusing break and continue.
continue will skip to next iteration in innermost loop
break will leave innermost loop
continue goes to the next iteration. You want break which exits the loop. See:
for i in range(10):
if i == 5:
continue
if i == 8:
break
print(i)
outputs:
0
1
2
3
4
6
7
I'm guessing the code you're trying to get at is as follows, which will print out each integer from 0 - 50 (exclusive), except it will print "I hit 33" for the integer 33.
x = 0
while x < 50:
if x == 33:
print("I hit 33")
else:
print(x)
x += 1
You really don't need the continue or pass in this instance. continue continues with the next cycle of the nearest enclosing loop. pass is usually only used as a placeholder when a block is expecting a statement but you're not ready to use the statement.

Breaking an if inside a while

I have the code below.
while True:
if 3 > 2:
break
Will the break return back to the while and cause an infinite loop, or will it break the while and continue in the flow?
continue skips current iteration.
break jumps out of the while. Starts executing code just right after it.
It will break the loop. Break is a break of the loop, an if else will only fire once if the condition is met.
break the while and continue in the flow
you can test this with some print:
while True:
if 3 > 2:
print("step1")
break
print("step2")
print("step3")

Categories