Why is the break statement in the code not working (python) - 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

Related

couldnt get output in python program

while True:
n = int (input ("What's n? "))
if n > 0:
break
for _ in range(n):
print("meow")
I can enter the input, but I could receive the output and I didn't have any error in my terminal window, please help where I went wrong.
Your for loop is inside your while loop and after the if statement. When your if statement evaluates to True (i.e. n > 0) then the break instruction will cause the program to exit the while loop. Thus, your for loop will never be executed.
You can learn more about the break statement from this tutorial.
The break statement in Python terminates the current loop and resumes
execution at the next statement
You can fix your code by moving the for loop outside of the while loop as follows:
while True:
n = int(input("What's n? "))
if n > 0:
break
for _ in range(n):
print('meow')

As long as there is a break statement (in any scope) within a while loop- when this is reached does the while loop terminate?

I have the following while loop:
while pointer < len(stack):
temp_string +=1
if stack[pointer] == "[":
break
pointer +=1
Now, I know that the break statement will cause the while loop to terminate, but am I right to say that as long as there is a break statement within the while loop (in any scope), as soon as it is reached, we break out of the while loop? i.e:
while pointer < len(stack):
temp_string +=1
if stack[pointer] == "[":
if ....:
if ...:
break
pointer +=1
So for the above, once we hit the break, it will break out of the while loop? Is this correct? And does the same apply to while loops within while loops?

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

Python continue Not Working Properly

I am writing a method using Python and I believe that the continue statement is not working properly. Can some explain to me what is wrong there?
The method code is below:
def xlToLinkedDt(lst1, lst2, name1, name2):
logging.info(">> New iteration")
dates1, times1, dates2, times2 = [], [], [], []
for i, (dt1, dt2) in enumerate(zip(lst1, lst2)):
if bool(dt1) + bool(dt2) == 1:
name = name1 if not dt1 else name2
issues.append("The %s date of trip no. %d must be provided." %(name, i+1))
dates1.append("")
dates2.append("")
times1.append("")
times2.append("")
logging.info("Exiting loop")
continue
logging.info(Continued after bool condition.)
raise AssertionError("Stop!")
When I run this code I get an error and the following logging in one of the iterations:
>> New iteration
>> Exiting loop
>> Continued after bool condition
The code is not supposed to log both messages, only one of them. Also when I replaced continue with break it worked well. What am I missing?
The code is not supposed to log both messages.
Yes, it is.
After your code executes continue, the loop moves back to the beginning of the block inside the for-loop, in the next iteration. If the condition in your if-block is not met at the next iteration, you will get exactly the behaviour you describe.
In [5]: for i in range(10):
print("Trying with i={:d}".format(i))
if i%2 == 0:
print("`i` even, continuing")
continue
print("What am I doing here?")
...:
Trying with i=0
`i` even, continuing
Trying with i=1
What am I doing here?
Trying with i=2
`i` even, continuing
Trying with i=3
What am I doing here?
Trying with i=4
`i` even, continuing
Trying with i=5
What am I doing here?
Trying with i=6
`i` even, continuing
Trying with i=7
What am I doing here?
Trying with i=8
`i` even, continuing
Trying with i=9
What am I doing here?
As you can see, there is still a What am I doing here? printed after the i even, continuing notification, but it belongs to a later iteration of the loop. If we replace continue by break, we get very different behaviour:
In [6]: for i in range(10):
print("Trying with i={:d}".format(i))
if i%2 == 0:
print("`i` even, not continuing")
break
print("What am I doing here?")
...:
Trying with i=0
`i` even, not continuing
As you can see, it stops immediately because (by our definition), 0 is even.
You used continue, I guess you meant break.
continue will skip to the next iteration of your for loop.
break will leave the for loop.
Try that :
def test():
print("Function start")
for i in range(10):
if i == 1:
print("Exiting loop")
continue
print("Am I printed or not ?")
print("I'm out of the loop")
Then replace continue by break and see what happens.
Since print("Am I printed or not ?") is part of the for loop, it will be executed on next for iteration after "Exiting loop", if you use continue. If you use break, it will be skipped.

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