Cornel Cornel - 2 months ago 8
Python Question

Break out of Python for loop

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.

Answer Source

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!")