I'm working with while loops and I'm just a bit confused on how to break out of it in the way that I want. So I've nested a for loop within a while loop:
x = True
y = 0
while x:
if y >= 5:
x = False
print('break')
else:
for x in range(7):
y += 1
print('test')
The output that I'm looking for is 5 tests printed out and one break. However, every time I run the program it prints out 7 tests before it goes to the break. I'm not exactly sure, but I think I'm just confused about something within while loops! If someone could explain this to me please let me know :) I have found ways around this, but I'd like to get an understanding of why it doesn't work.
This is because it's performing the entire for loop within the while loop therefore y will become 7 before it checks again. Removing the for loop will resolve this.
x = True
y = 0
while x:
if y >= 5:
x = False
print('break')
else:
y += 1
print('test')
y = 0
while y < 5:
print("test")
y += 1
print("break")
Would work.
There is no point in having another variable like "x" for the while loop when it allows for you to set the condition directly.
Because inner loop will complete before the next iteration of the outer loop. I.e. once the inner loop starts it does all 7 iterations before starting the next iteration of the while loop.
You can do this by just using one loop. Print out “test” increase counter and put in an if condition to break when counter is 5.
The reason 7 tests print rather than 5 is that your entire for loop is executed before you go back to the beginning of your while statement. I think your understanding is that, after one iteration of a for loop, you go back to the beginning of the while loop, but this is incorrect: your for loop is executed completely before going back to the beginning of the while loop.
After you step into the for loop, you increment y 7 times and print test 7 times. y is now >= 5, and you go back into your if statement. The if statement turns x false, thereby "turning off" the while loop, and a break statement is printed. If you just want to print out 5 tests and one break, it would be much easier to simplify your code as such:
y = 0
while True:
if y < 5:
print('test')
y += 1
else:
print('break')
break
Try
i = 0
while True:
if i == 5:
break
print('test')
i = i + 1
Related
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
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
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.
Is there a way to get a for loop to start again at any point within the loop? Say line has a length of three. If the if statement is satisfied and my index increments, I want everything to start checking again at the first value of line.
(Note this whole thing is part of a while True loop).
for line in library:
if message[index:index + len(line)-2] == line[2:]:
ans += line[0]
index += len(line)-2 + 1
I think you need another while True above the for loop.
For example, this is a continuous loop unless there is a break condition
x = [1, 2, 3, 4, 5, 6]
restart = True
while restart:
for i in x:
# add any exit condition!
# if foo == bar:
# restart = False
# break
if i == value: # add your message condition
break
You could replace x with library in your case and i with line. Then instead if i == 4 you add your break condition that resets the loop and if you do have an actual break condition, you set the restart flag to False
Another option would be using a loop counter like n = 2 and use while n < 2: and then set n += 1 whenever your condition mets or n = 0 whenever you want to reset.
If I'm reading it right you want to entirely restart the loop when you find a match. Easiest way to do this is by breaking out of the for loop as you stated you have a while loop above it which remains True and will restart the for loop:
for line in library:
if message[index:index + len(line)-2] == line[2:]:
ans += line[0]
index += len(line)-2 + 1
break
how exactly will you know if it will not terminate? is there a function that makes it keep on going? If i want to stop the loop after a certain number of times, how would i do it?
Generally, it's impossible to know ahead of time whether a program will loop forever or eventually stop. This is called the Halting problem. Of course, in practice you can probably make a reasonable guess just by looking at the condition.
a while loop will keep going as long as its condition is true. You do not need a function to make it keep going.
while True:
print "hello, world!"
#no functions required here!
If you want something to loop a certain number of times, it's preferable to use a for loop:
for i in range(10):
print "hello, world!"
#prints ten times
although you still can use a while loop if you really want.
count = 0
while count < 10:
print "hello, world!"
count += 1
A while loop is terminated
if the condition it uses is false at the time it gets evaluated.
Example:
x = 10
while x > 5:
x -= 7
print x
x += 6
print x
successively will print the numbers 3, 9, 2, 8, 1, 7, 0, 6, -1, 5 and only then terminate.
x becomes <= 5 during execution, but only the state at the time where the loop is restarted is relevant.
if it is left meanwhile with break:
x = 10
while x > 5:
print x
x -= 1
break
only prints 10, because it is left "forcefully" afterwards.
A loop which runs a certain number of times would be done
x = 0
while x < n:
do_stuff()
x += 1
or better with for:
for x in range(n):
do_stuff()