Back in a code while loop - python

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.

Related

Why does the while loop never stop looping?

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)

Basic While Loop sequence of iteration?

For the code below, after the first instance where the IF statement is false (i.e. for i=9), I understand that we go to the print("something") step however, my question is why does it infinitely print "something" and "somethingelse" instead of printing these two just once each then just ending? I mean we have no step after the print of these two that tells it to go back to the if statement and test again with i = 9 (that would lead to an infinite loop)..
i=1
while True:
if i%9 != 0:
print ("inside if")
i +=1
continue
print("something")
print("somethingelse")
Your print statements are inside of a While True: loop with no exit criteria. That is precisely why.
while True:
Means that while I do not have a statement somewhere to stop or a break to stop the algorithm, it will keep entering in the while loop.
Therefore, what you made is an infinite loop and that's why it keeps printing the same stuff.
i=1
while True:
if i%9 != 0:
print ("inside if")
i +=1
break
print("something")
print("somethingelse")
#output
"inside if" -> breaks after `i=1` because `1%9=1`
"something"
"somethingelse"
i=1
kak = True
while kak:
if i%9 != 0:
print ("inside if")
i +=1
kak = False # --> something to tell the algorithm, hey! stop!
print("something")
print("somethingelse")

True while loop python

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

Break out of while True loop with function

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.

python - check at the end of the loop if need to run again

It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;
"loop again? y/n"
while True:
func()
answer = raw_input( "Loop again? " )
if answer != 'y':
break
keepLooping = True
while keepLooping:
# do stuff here
# Prompt the user to continue
q = raw_input("Keep looping? [yn]: ")
if not q.startswith("y"):
keepLooping = False
There are two usual approaches, both already mentioned, which amount to:
while True:
do_stuff() # and eventually...
break; # break out of the loop
or
x = True
while x:
do_stuff() # and eventually...
x = False # set x to False to break the loop
Both will work properly. From a "sound design" perspective it's best to use the second method because 1) break can have counterintuitive behavior in nested scopes in some languages; 2) the first approach is counter to the intended use of "while"; 3) your routines should always have a single point of exit
While raw_input("loop again? y/n ") != 'n':
do_stuff()

Categories

Resources