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)
Related
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")
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
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.
Is there any way to break out of infinite loops using functions? E.g.,
# Python 3.3.2
yes = 'y', 'Y'
no = 'n', 'N'
def example():
if egg.startswith(no):
break
elif egg.startswith(yes):
# Nothing here, block may loop again
print()
while True:
egg = input("Do you want to continue? y/n")
example()
This causes the following error:
SyntaxError: 'break' outside loop
Please explain why this is happening and how this can be fixed.
As far as I'm concerned you cannot call break from within example() but you can make it to return a value(eg : A boolean) in order to stop the infinite loop
The code:
yes='y', 'Y'
no='n', 'N'
def example():
if egg.startswith(no):
return False # Returns False if egg is either n or N so the loop would break
elif egg.startswith(yes):
# Nothing here, block may loop again
print()
return True # Returns True if egg is either y or Y so the loop would continue
while True:
egg = input("Do you want to continue? y/n")
if not example(): # You can aslo use "if example() == False:" Though it is not recommended!
break
The way to end a while-true loop would be to use break. Furthermore, the break must be in the immediate scope of the loop. Otherwise, you could utilize exceptions to hand control up in the stack to whatever code handles it.
Yet, oftentimes it's worth considering another approach. If your example is actually close to what you really want to do, namely depending on some user prompt input, I'd do it like this:
if raw_input('Continue? y/n') == 'y':
print 'You wish to continue then.'
else:
print 'Abort, as you wished.'
An alternative way to break out of a function inside of a loop would be to raise StopIteration from within the function, and to except StopIteration outside of the loop. This will cause the loop to stop immediately. E.g.,
yes = ('y', 'Y')
no = ('n', 'N')
def example():
if egg.startswith(no):
# Break out of loop.
raise StopIteration()
elif egg.startswith(yes):
# Nothing here, block may loop again.
print()
try:
while True:
egg = input("Do you want to continue? y/n")
example()
except StopIteration:
pass
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()