I've been trying to understand this for a while now and I don't get why the true while loop doesn't exit when the check() function returns False value and asks input(i.e "enter input")again and again but it exits when else statement of func() function returns False value. No matter what,as far as I know, the while loop should stop or exit when the value returned is false, but that isn't the case here. I don't intend to modify the code but would just like to understand the concept behind this. please help me. Thanks! in advance.
def check(num):
if(num%2==0):
return True
else:
return False
def func():
temp=[str(i) for i in range(1,51)]
while True:
c=input("enter input: ")
if c in temp:
c=int(c)
if check(c):
print(c)
break
else:
print("input invalid, enter only digits from 1 to 50")
return False
It would most likely be due to the fact that the while true loop being used in the func() function is local to that function and so when you try to use the other function check() to actually change the value, it cannot do so. It would only be able to return false or true for a while loop that is included in the same function.
To exit a loop (for or while) outside a function or exit within the funtion but only exiting the loop you should use break instead of return.
The blank return that you have doesn't actually do anything.
You will have to break from the loop.
It works in the second case as you actually return a value like False
You could try doing this:
loop = True
def check(num):
global loop
if(num%2==0):
loop = False
else:
loop = False
def func():
global loop
temp=[str(i) for i in range(1,51)]
while loop:
c=input("enter input: ")
if c in temp:
c=int(c)
if check(c):
print(c)
loop = False
else:
print("input invalid, enter only digits from 1 to 50")
loop = False
Related
well i've a loop in which i want to enter only for once when condition is satisfied and then again it should enter after a variable value gets changed.
class OMS:
timeframe_check = 1
def upside_ex(self,tickers):
for ticker in tickers:
try:
order_placed = False
if self.timeframe_check == latest_time:
if order_check_1st_sca == True and not order_placed:
self.PlaceOptionOrderBuy(tickers,"buy",quantity)
order_placed = True
if order_check_1st == True and not order_placed:
self.PlaceOptionOrderBuy(tickers,"buy",quantity)
order_placed = True
else:
order_placed = False
self.timeframe_check += 1
print(self.timeframe_check , "this is timeframe_check from else which got incremented")
break
except Exception as e:
print(e)
pass
i want to enter inside the inside the if loop when both timeframe_check and latest_time are equal and make the order_placed as true so that it'll not enter inside the loop until and unless it's made false again.
But the issue is in the first iteration it's entering the if loop but when the second iteration comes it only enters the else loop and does the increment. after increment it should again enter the if loop but it's not doing it as expected.
Because at the same time it's shows timeframe_check as 1 and also inside the else loop timeframe_chcek as 2 after incremented but then why it's not entering the if loop after the incrementing.
you using break. So after getting incremental you are breaking out of the loop that's why next time loop doesn't iterate. You can use pass instead.
Below is the snippet of my code. Let's assume that the output of play_again() inside the while loop returns False. Then, why does my while loop keep on looping? Is there is some concept I'm unaware of?
game_list = ['0','1','2']
while True:
position = myfunc()
replacement(game_list,position)
play_again()
print(game_list)
this is b/c the while True does not end unless you use the keyword break wich breaks outside the loop and continues the code.
the while True never ends
the while loop
while (condition):
#code
never ends until the condition is False, witch would never be true for the True condition.
do your code should be:
game_list = ['0','1','2']
while True:
position = myfunc()
replacement(game_list,position)
if not play_again():
break
print(game_list)
or you could do:
game_list = ['0','1','2']
while play_again():
position = myfunc()
replacement(game_list,position)
print(game_list)
This code should work:
while (play_again()):
position = myfunc()
replacement(game_list,position)
You should know that in Python a while loop (like in every other programming language) takes a single "argument", that is a condition of type bool:
while (i > 3): # i>3 is a boolean condition
...
In fact this is equivalent to
while (True): # the loop continues until condition is False, so in this case it will never stop
if (i > 3):
break
In Python break is a keyword that makes you exit the loop.
Then, as you probably understood, this code is equivalent to the first snippet in this answer:
while (True):
position = myfunc()
replacement(game_list,position)
if (not play_again()):
break
while True will run until you decide to break.
game_list = ['0','1','2']
while True:
position = myfunc()
replacement(game_list,position)
play_again = input("do you want to play again?")
if play_again == 'y':
play_again()
else:
break
print(game_list)
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
So I have a while true loop -
while True:
getStatus()
print('Ended')
I hope to be able to break out of it if answer is 999. this is what I tried:
def getStatus():
answer = input('What is the box ID? ')
if answer == 999:
return False
elif type(answer) == int:
boxId = answer + 1
print(boxId)
However even when the input is '999' it loops back and asks 'What is the box ID? ' again.
How do I get out of the while true loop?
Your while loop keeps looping because that's exactly what you've told it to do. After the function you call from its body returns, you ignore the return value, unconditionally print "Ended" and then do it all again, since the condition on the loop is obviously still truthy.
If you want the function to control if the loop keeps going, you should use its return value as the condition in the loop, with something like this:
running = True
while running:
running = getStatus()
print("Ended") # move this outside the loop!
This requires that getStatus returns a truthy value when you want to keep looping and a falsey value when you want to stop. Your current implementation of that function doesn't do that. It returns False when 999 is entered, but doesn't explicitly return anything if you give other input (which in Python is equivalent to returning None). Since both False and None are falsey, the code above won't actually work (you could patch it with something like running = getStatus() is None, but that would be horrible). You should change the function to have an explicit return statement in all of its branches (including the case for non-integer inputs, where it doesn't go into either your if or elif blocks).
If the loop and the function's logic are tightly intertwined, it might make sense to move the loop into the function itself, rather than having it be separate and needing to use a return value to signal when to stop. In a single function, you can use break to exit a loop directly:
def getStatus():
while True:
answer = input('What is the box ID? ')
if answer == 999:
break
elif isinstance(answer, int): # isinsance() is better than type(...) == ...
boxId = answer + 1
print(boxId)
else:
print("I'm sorry, I didn't understand that.") # still good to handle this case
you can add if statement before get_status() that will check if it's true and break and in the get_status function you will have to return true to break
def getStatus():
answer = input('What is the box ID? ')
if answer == 999:
return True
elif type(answer) == int:
boxId = answer + 1
print(boxId)
while True:
if getStatus():
print('Ended')
break
def selectedCountry():
while True:
country = input("Enter country of which you want to check pictures HR, RS, RO: ").upper()
if country == str("HR") or country == str("RO") or country == str("RS"):
break
else:
print("Please enter HR or RO or RS: " + "you wrote: " + country)
Why while True is working outside of a function and inside the same problem with asking again
Enter country of which you want to check pictures HR, RS, RO: >? hr
Enter country of which you want to check pictures HR, RS, RO:
You may change it to -
while True:
if(getStatus()==False):
print('Ended')
break
By this you can use returned value to break out of infinite loop.
I have a problem in a simple code with while loop. My problem is explained in code comments.
CODE
exit = False
while not exit:
choice = input("Test ")
if choice== 1:
print "hello"
exit = False
else:
print "good morning"
#I want to return to the first while with the input Test but I pass to the second while
exit = False
exit1 = False
while not exit1:
choice = input("Test 1")
if choice== 1:
print "bye"
exit1 = False
else:
print "good evening"
#I want to return to the first while with the input Test but I return to the second while
exit = False
Thanks a lot.
I think what are you looking for are the continue and break statements.
The continue will interrupt the current iteration (and a new iteration is started, of course).
The break will interrupt the smallest enclosing loop.
Both statements work for for as well.
Take a look here for some reference.
outer = True
while outer:
do_something
if a:
continue # will get you back to do_something
if b:
break # will end the outer loop
If you set outer to False somewhere, it will end the while loop in the next iteration.