Break outside of two loops - python

I'm writing a code with a while loop inside a while loop and am wondering how to break out of the outer loop if I meet the necessary conditions in the inner loop.
while N <= 8:
while i < 60:
if this:
that
elif this:
that other thing
else:
break
i += 1
if while loop has found the right thing:
N += 1
else:
change conditions
This break command will only break out of the first loop, so I'm wondering how to simply break out both. It might be worth mentioning that all this is in another for loop which I wouldn't want to break out of. Thank you.

Encapsulate it in a function and return when you are done?

Use a flag; trigger is used here
trigger = False
while N <= 8:
while i < 60:
if this:
that
elif this:
that other thing
else:
trigger = True
break
i += 1
if trigger:
break
elif while loop has found the right thing:
N += 1
else:
change conditions

Use flag:
flag = True
while N <= 8:
while i < 60:
if this:
that
elif this:
that other thing
else:
flag = False # To exit from outer while loop
break
i += 1
if(not flag):
break # Condition in inner loop is met
if while loop has found the right thing:
N += 1
else:
change conditions

Related

If statement returning False in While True loop (Python)

I expected that in this If statement, the variable 'i' would increment until it eventually equals 10, and subsequently 'if 10 < 10' would return False, breaking my while loop. But this code seems print until 10 and then get stuck in an infinite loop unless I add an else: break. Why?
i=0
while True:
if i < 10:
i = i + 1
print(i)
while X repeats when X equals to True so in while True it's always True. It only breaks with break statement.
In your code, you only check the value inside the while loop with if so neither you break the while loop nor you change True to False in while True.
If you want to use while:
i = 0
while i < 10:
i += 1
print(i)
Or
i = 0
while True:
if i < 10:
i += 1
print(i)
else:
break
Without while:
for i in range(10):
print(i)
while True
will make the loop run forever because "true" always evaluates to true. You can exit the loop with a break.
To achieve what you want to do, I would use
while i < 10:
print (i)
i++
That is because there isn't anything telling you to terminate the loop. So it will continue even after the if statement isn't satisfied.
This is why it is generally not a great practice to use while True
You can achieve the same thing with a for loop when the break condition is built into the loop:
for i in range(0, 10):
print(i)
If you want to use while True then you can go for:
i=0
while True:
i = i + 1
print(i)
if i == 10:
break
I think you need to understand a few things here, as you have set while True which means statement will never gets false so there is never end to while loop even if if condition gets fail. So the while loop will continue running till you interrupt.
The only way you can achieve this without break is like this, where you have a variable which will reset the condition of while loop to false when if loop fails
i=0
condition = True
while condition:
if i<10:
i=i+1
print(i)
else:
condition=False

Python For loops with while and if statements: Why doesnt it return in the first case?

Hey guys I know this question might seem dumb, but I just started. This is Python 3.7.
Any way I have written 2 versions of the code, the second one works, but I've added another while loop where I thought it wasn't needed. Why doesn't the first version work? Its iterating a list of numbers (nums).
This is from a problem statement:
Write a function that takes in a list of integers and returns True if it contains 007 in order.
spy_game([1,2,4,0,0,7,5]) --> True
spy_game([1,0,2,4,0,5,7]) --> True
spy_game([1,7,2,0,4,5,0]) --> False
My first code was this, and it always returned False:
z = 0
for i in nums:
while z < 2:
if i != 0:
break
else:
z += 1
break
if i != 7:
break
else:
return True
return False
Why does this change, make it work?
z = 0
for i in nums:
while z < 2:
if i != 0:
break
else:
z += 1
break
while not z < 2:
if i != 7:
break
else:
return True
return False
Thanks very much!
Your problem is the way you're using the while-loop. The code in the while-loop is executed as long as the condition is met. However, you call a break or return inside the while-loop in each way.
So what you actually want to use is an if-statement instead of the while-loop. Then the break would work the way you expected it to work in the first example. The break makes the program jump out of the current loop, that is the while-loop. But for the first example to work correctly, it should jump out of the higher for-loop. Using if instead of while should fix this.
Maybe try something like this:
z = 0
for i in nums:
if z < 2:
if i == 0:
z += 1
else:
if i == 7:
return True
return False

While loop that's meant to be infinite freezes after first cycle

My goal is to make a program that prints onscreen all of the prime numbers it can find, however I have this issue where the while loop runs only once, instead of repeating forever.
def isPrime(num):
if num < 2:
return False
if num == 2:
return True
if num % 2 == 0:
return False
i = 3
while i * i <= num:
if num % i == 0:
return False
i += 2
x = 1
while True:
x += 1
if isPrime(x):
print (x)
I also have tried adding print("You can see this.") at the very end of the code, and it runs, but only once.
I'm sure it's a common mistake, since Python is very strict on indentation, but could you guys help me discover it? Thanks in advance.
You need to return True at the very end, after and outside the final loop. Otherwise the function ends without explicitly returning anything, so it implicitly returns None which is interpreted as false.
The i +=2 is indented too deep, the inner loop never quits.
It should read
while i * i <= num:
if num % i == 0:
return False
i += 2
Otherwise i never increases and the loop goes on and on and on.

Ending a program

How do I end my program if something is true?
This is my code
count=0
num=input("What would you like to do [1,2,3,4]? ")
while (num>'0' and num<'5'):
while num=='1':
Do something
while num=='2':
Do something
While num=='3':
Do something
while num=='4' and count!=1:
print("The End")
count= count+1
I want the program to end while num is '4'
First of all use integers not strings:
>>> '100' > '5'
False
And use if instead of while, if any of the conditions is True then you can use the break statement to break out of the loop.
count = 0
num = int(input("What would you like to do [1,2,3,4]? "))
while 0 < num < 5:
if num == 1:
Do something
...
if num == 4 and count != 1:
print("The End")
count += 1
break #breaks out of the `while` loop
Also note that you should use if-elif-else conditions here instead of just if's, because here all if conditions are going to be checked, but with if-elif-else conditions will short-circuit(jump to the end of if-elif-else block) as soon as one of the condition is True.
Use
if num=='4' and count!=1:
not
while num=='4' and count!=1:
Add a break statement and use numbers
while (num > 0 and num < 5):
while num == 1:
#Do something
while num == 2:
#Do something
while num == 3:
#Do something
if num == 4 and count != 1:
print ("The End"); count += 1
break
Use if in place of while loop like,
while (num>0 and num<5):
if num==1:
Do something
if num==2:
Do something
if num==3:
Do something
if num==4 and count!=1:
print("The End")
count= count+1
break

Opposite of Python for ... else

The following Python code will result in n (14) being printed, as the for loop is completed.
for n in range(15):
if n == 100:
break
else:
print(n)
However, I want the opposite of this. Is there a way to do a for ... else (or while ... else) loop, but only execute the else code if the loop did break?
There is no explicit for...elseifbreak-like construct in Python (or in any language that I know of) because you can simply do this:
for n in range(15):
if n == 100:
print(n)
break
If you have multiple breaks, put print(n) in a function so you Don't Repeat Yourself.
A bit more generic solution using exceptions in case you break in multiple points in the loop and don't want to duplicate code:
try:
for n in range(15):
if n == 10:
n = 1200
raise StopIteration()
if n > 4:
n = 1400
raise StopIteration()
except StopIteration:
print n
I didn't really like the answers posted so far, as they all require the body of the loop to be changed, which might be annoying/risky if the body is really complicated, so here is a way to do it using a flag. Replace _break with found or something else meaningful for your use case.
_break = True
for n in range(15):
if n == 100:
break
else:
_break = False
if _break:
print(n)
Another possibility, if it is a function that does nothing if the loop doesn't find a match, is to return in the else: block:
for n in range(15):
if n == 100:
break
else:
return
print(n)
Use:
for n in range(15):
if n == 100:
break
else:
print("loop successful")
if n != range(15)[-1]:
print("loop failed")

Categories

Resources