Does raw_input() stop an infinite while loop? - python

There is a small code below containing of while-loop.
question = raw_input("How are you? > ")
state = True
number = 0
print "Hello"
while True:
if question == "good":
print "Ok. Your mood is good."
state = False
question_2 = raw_input("How are you 2? > ")
elif question == "normal":
print "Ok. Your mood is normal."
elif question == "bad":
print "It's bad. Do an interesting activity, return and say again what your mood is."
else:
print "Nothing"
If I type in "normal", the program prints Ok. Your mood is normal. an infinite number of times.
But if I type in "good", the program prints Ok. Your mood is normal. and prints the contents of question_2.
Why is the question in question_2 = raw_input("How are you 2? > ") not repeated an infinite number of times?
Is it reasonable to conclude that raw_input() stops any infinite while loop?

No. It's not stopping the loop; it's actively blocking for input. Once input is received, it will not be blocked anymore (and this is why you get infinite text from other selections); there is no blocking I/O in those branches.
The reason you're not getting a lot of text output from option 1 is due to the way it's being evaluated. Inside of the loop, question never changes, so it's always going to evaluate to "good" and will continually ask you the second question1.
1: This is if it is indeed while True; if it's while state, it will stop iteration due to state being False on a subsequent run.

Once you've answered "good, the value returned by the second raw_input will be stored in variable question_2 rather than question. So variable question never changes again, but will remain "good". So you'll keep hitting the second raw_input, no matter what you answer to it. It doesn't stop your loop, but rather pauses it until you answer. And I think you should also take a good look at the comment of Alfasin...

You can stop an infinite loop by having an else or elif that uses a break for output. Hope that helps! :D
Example:
while True:
if things:
#stuff
elif other_things:
#other stuff
#maybe now you want to end the loop
else:
break

raw_input() does not break a loop. it just waits for input. and as your question is not overwritten by the second raw_input(), your if block will always end up in the good case.
a different approach:
answer = None
while answer != '':
answer = raw_input("How are you? (enter to quit)> ")
if answer == "good":
print( "Ok. Your mood is good.")
elif answer == "normal":
print( "Ok. Your mood is normal.")
# break ?
elif answer == "bad":
print( "It's bad. Do an interesting activity, return and say again what your mood is.")
# break ?
else:
print( "Nothing")
# break ?

Related

Python While loop breakout issues

The question I have is about the flag I have here for the while loop. This works but not like I think it should. I assume I'm not understanding something so if someone is able to explain, that would be great.
From my understanding this should break out of the loop as soon as one of my conditionals is met. So if I input 'q' it should break out and stop the loop. But what happens is it keeps going through the loop and then it breaks out. so it goes through the last prompt and prints the exception.
(Python version is 3.8.5)
# Statement that tells the user what we need.
print("Enter two numbers and I will tell you the sum of the numbers.")
# Lets the user know they can press 'q' to exit the program.
print("Press 'q' at anytime to exit.")
keep_going = True
# Loop to make the program keep going until its told to stop.
while keep_going:
# Prompt for user to input first number and store it in a variable.
first_number = input("First number: ")
# Create a break when entering the first number.
if first_number == 'q':
keep_going = False
# Prompt for user to input second number and store it in a variable.
second_number = input("Second number: ")
# Create a break when entering the second number.
if second_number == 'q':
keep_going = False
# Exception for non integers being input "ValueError"
try:
# Convert input to integers and add them.
# storing the answer in a variable.
answer = int(first_number) + int(second_number)
except ValueError:
# Tell the user what they did wrong.
print("Please enter a number!")
else:
# Print the sum of the numbers
print(f"\nThe answer is: {answer}")
Using this code it breaks out right away like I expect it to.
while True:
first_number = input("First number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
I just would like to understand what the difference is and if thats how it should work. I feel like I'm missing something or misunderstanding something.
The condition of the while loop is only checked between iterations of the loop body, so if you change the condition in the middle of the loop, the current iteration will finish before the loop terminates. If you want to break a loop immediately, you need to either break (which automatically breaks the loop regardless of the condition) or continue (which jumps to the next iteration, and will therefore terminate the loop if the condition is no longer true).
Using while True: with a break when you want to stop the loop is generally much more straightforward than trying to control the loop by setting and unsetting a flag.
FWIW, rather than copying and pasting the code to input the two numbers, and have two different ways to break out of the loop, I might put that all into a function and break the loop with an Exception, like this:
print("Enter two numbers and I will tell you the sum of the numbers.")
print("Press 'q' at anytime to exit.")
def input_number(prompt: str) -> int:
"""Ask the user to input a number, re-prompting on invalid input.
Exception: raise EOFError if the user enters 'q'."""
while True:
try:
number = input(f"{prompt} number: ")
if number == 'q':
raise EOFError
return int(number)
except ValueError:
print("Please enter a number!")
while True:
try:
numbers = (input_number(n) for n in ("First", "Second"))
print(f"The answer is: {sum(numbers)}")
except EOFError:
break
This makes it easier to extend the program to handle more than two inputs; try adding a "Third" after where it says "First" and "Second"! :)
Once you run the program and type "q", Yes indeed keep_going will be set to False but it DOES NOT MEAN it will break the loop already, it will just make the keep_going be equal to False thus on the NEXT ITERATION will stop the loop. Why is that? because it would be like this while keep_going: -> while False: so since it is not True thus not executing the program anymore.
Now based on your goal as you mentioned. You can do it this way where you can add the break.
if first_number == 'q':
keep_going = False
break
# Prompt for user to input second number and store it in a variable.
second_number = input("Second number: ")
# Create a break when entering the second number.
if second_number == 'q':
keep_going = False
break
I'd also like to suggest have it this way, it's just more specific in terms of what is to happen on the code, but of course it is up to you.
first_number = input("First number: ")
# Create a break when entering the first number.
if first_number == 'q':
keep_going = False
break
# Prompt for user to input second number and store it in a variable.
# Create a break when entering the second number.
else:
second_number = input("Second number: ")
if second_number =='q':
keep_going = False
break
While loops execute until their given condition is false. A loop will only check its condition when required (program execution is moved to the top of the loop). In almost every case, this occurs when the full body of the loop has run. See here:
keep_going = True
while keep_going:
keep_going = False
# keep_going is False, but this will still print once
# because the loop has not checked its condition again.
print("Will execute once")
"Will execute once" prints a single time even after keep_going is set to False. This happens because the while loop does not re-check its condition until its entire body has run.
However, break statements are different. A break statement will cause a loop to exit immediately no matter what.
keep_going = True
while keep_going:
break # Exits the while loop immediately. The condition is not checked.
print("Will never print")
Here, nothing is printed even though keep_going is True the whole time. break made the loop exit regardless of the condition.
A continue statement will move program execution back to the start of the loop, and cause your condition to be checked again.
In this example, continue sends program execution back to the start of the loop. Since keep_going was set to False, nothing will print because the while loop will exit after realizing its condition evaluates to false.
keep_going = True
while keep_going:
keep_going = False
continue
print("Will never print")
First off, hope you have a great time learning Python!
Both ways will work and stop the loop, but there is a difference:
In the first method, you are changing the keep_going variable to false, therefore, the loop will stop when the the while loops finds out that keep_going had become False. However, the checking only happens at the end of the loop (In your case, it is after you have done your except or else part), the loop will not stop right away even when you entered q for your variable first_number.
In the second solution, you are using the break keyword in Python, to break away from the loop right away after you entered q for first_number.
Technically speaking, you will want to break if you want to break off from the loop right away when q is detected, otherwise, setting keep_going to False if you want the whole loop to be completed, but not run again for the next round.
In scenario 1 the result, even when you entered q,
Please enter a number!
Will always show, but not for scenario 2.
this is a little different approach to your script:
def main():
print("Enter two numbers and I will tell you the sum of the numbers.")
print("Press 'q' at anytime to exit.")
val = []
while True:
check_value = lambda x: 'quit' if x.lower() == 'q' or x.lower() == 'quit' else int(x)
if not val:
value = input("First number: ")
elif len(val) == 2:
answer = sum(val)
print(f"\nThe answer is: {answer}")
print('==='*15 + ' < ' + f'PROGRAM RESTARTING' + ' > ' + '==='*15)
val[:] = []
continue
else:
value = input("Second number: ")
try:
check_ = check_value(value)
val.append(check_)
except ValueError:
print("Please enter a number!")
continue
finally:
if check_ == 'quit':
print('Program is stopping....')
break
else:
pass
if __name__ == '__main__':
main()
It check at anytime the user's input, whether is a 'q' 'Q' or ('quit' or 'QUIT') or any combination or capital letter because run the check x.lower()
I suggest you to have a look at realpython.com especially the paragraph "he Python break and continue Statements."
Long story short:
Use Break to terminate the loop at any given time.
Use continue to roll back where you left and repeat the loop again (I used it in my code if the value is not a Int)
User pass to keep the loop running with no stop.

Number correcting

Im writing code with a part that is confusing me.
while answer1 != 'a':
if answer1 == 'b':
print('\nWrong answer.\n')
answer1= input("\nEnter again.\nYou only have one more try!\n")
amount = amount+1
print(amount)#for testing
if amount == 1:
print("\nTry next question")
break
What I want to do is to have the tries to be two if the user said 'b' twice. I have put amount as 1 but if the user says a, then it will be two. What I want to do is to have the tries to two if 'b' is said twice but one if 'a' is said once.
So, the overall goal here is unclear. However, I think this may help you out:
First of all, drop the while answer != 'a', and go to while True, rely on the conditional inside the loop to handle break / continue.
amount = 1 # Initiate amount outside of the loop, otherwise it'll get reset on each loop.
while True: # Run until base condition is met.
print("I am the question")
ANSWER = input("Answer: ")
if ANSWER == 'a' or amount >= 2: # Base condition.
print(amount)
break
else: # This runs if answer isn't what you want.
print("Wrong, please try again.")
amount += 1
continue
Best

How to get program to restart without using break? [duplicate]

This question already has answers here:
How do I restart a program based on user input?
(6 answers)
Closed 6 years ago.
answer = input('how are you')
if answer == 'good':
print('glad to hear it')
if answer == 'what?':
print('how are you?')
Without using break, how do I start at the beginning again if the user were to input 'what?' How would I do this with only variables and loops?
''' it keeps looping till the answer is .good. No flags are used '''
answer='#'
while(answer != 'good'):
answer = input('how are you\n')
if answer == 'good':
print('glad to hear it')
This should work properly:
good = False
while not good:
answer = input('how are you?')
if answer == 'what?':
continue
if answer == 'good':
good = True
print('glad to hear it')
When the variable good becomes True, the loop stops. The continue skips to the next iteration of the loop, but, it's not necessary. Leaving it there shows the reader that 'what?' is an expected input.
Now, you said you can't use break, but, if you could, it would look like this:
while True:
answer = input('how are you?')
if answer == 'what?':
continue
if answer == 'good':
print('glad to hear it')
break
You don't need anything complicated to achieve that.
input = '' #nothing in input
while input != 'good': #true the first time
input = raw_input('how are you?') #assign user input to input
if input == 'good': #if it's good print message
print('glad to hear it')
or
input = 'what?' #what? in input
while input == 'what?': #true the first time
input = raw_input('how are you?') #assign user input to input
if input == 'good': #if it's good print message
print('glad to hear it')
else:
print('too bad')
The first case if you're expecting good or the second if any reply works except what?.

python looping with functions break and continue outside loop

I am new to programming and so i'm practicing a bid. At this point i'm practicing with functions. In the code below break and continue are outside the loop i can not see why. I've tryed out different ways but the only thing i get to work is the last block of code. Why are break and continue outside the loop here?
import random
again = 'y'
while again == "y" :
def main():
print "gues a number between 0 - 10."
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print 'Your the man'
found = True
else:
print 'to bad dude try again'
main()
again = raw_input('would you like to play again press y to play again press n yo exit')
if again == 'n':
break #here it says it is outside the loop
elif again != 'y':
print 'oeps i don\'t know what you mean plz enter y to play again or n to exit'
else:
continue #this is outside loop as well
#main()
Because you are new to programming, I will get a few basic tips in my answer too.
INFINITE LOOP
You are trying to start an infinite loop by first settingagain = 'y' and afterwards you are using this variable to evaluate a while loop. Because you are not changing the value of y, it is better to not use a variable to create this infinite loop. Instead, try this:
while True:
(some code)
DEFINE FUNCTION IN LOOP
You're defining the function main() inside of the while loop. As far as I can tell, there is no use for that. Just leave out the first while loop. If you define a function, it is permanent (much like a variable), so no need to redefine it everytime. Using your code, you won't even get to call the function, because you never end the first loop.
CONTINUE/BREAK NOT IN LOOP
The error is quite self-explanaitory, but here we go. If you would ever end the first loop (which in this case, you won't), the next thing you do is call your function main(). This will generate a number and make the user guess it until he got it right. When that happens, you get out of that function (and loop).
Next, you ask if the user would like to play again. This is just an input statement. You store the answer in the variable 'again'. You check, with an if statement (note that this is not a loop!) what the answer is. You want the user to play again if he typed 'y', so instead of using again != 'y', you could use the following:
if again == 'y':
main() # you call the function to play again
If 'n' was typed in, you want to exit the script, which you do not by typing break, because you are not in a loop, just in an if-statement. You can either type nothing, which will just go out of the if-statement. Because there is nothing after the if, you will exit the script. You could also useexit(), which will immediately exit the script.
Lastly, you want to repeat the question if neither of these two things were answered. You can put the if-statement inside of a loop. You can (if you want) use your break and continue when doing this, but you mostly want to avoid those two. Here is an example:
while True:
again = raw_imput('y for again or n to stop')
if again == 'y':
main()
exit() # use this if you don't want to ask to play again after the 2nd game
elif again == 'n':
print('bye!')
exit()
# no need for an 'else' this way
# every exit() can be replaced by a 'break' if you really want to
BASIC BREAK/CONTINUE USAGE
Finally, here is some basic usage of break and continue. People generally tend to avoid them, but it's nice to know what they do.
Using break will exit the most inner loop you are currently in, but you can only use it inside of a loop, obviously (for-loops or while-loops).
Using continue will immediately restart the most inner loop you are currently in, regardless of what code comes next. Also, only usable inside of a loop.
EVERYTHING TOGETHER
import random
again = 'y'
def main():
print ("gues a number between 0 - 10.")
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print ('Your the man')
found = True
else:
print ('to bad dude try again')
main()
while True:
again = input('would you like to play again press y to play again press n yo exit')
if again == 'n':
print ('bye!')
exit() # you could use break here too
elif again == 'y':
main()
exit() # you can remove this if you want to keep asking after every game
else:
print ('oeps i don\'t know what you mean plz enter y to play again or n to exit')
I hope I helped you!
You loops and def are all muddled, you want something more like:
import random
again = 'y'
while again == "y" :
print "gues a number between 0 - 10."
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print 'Your the man'
found = True
else:
print 'to bad dude try again'
while True:
again = raw_input('would you like to play again press y to play again press n to exit')
if again == 'n':
break
elif again != 'y':
print 'oeps i don\'t know what you mean plz enter y to play again or n to exit'
else:
break
You may want to refer to instructional material because you seem to misunderstand the general purpose of functions and the order of your logic.
Your function should be at the outer scope, e.g.:
def main():
again = 'y'
while again == "y" :
Your question for again needs to be indented into the while loop:
while again == "y":
[snip]
again = raw_input('would you like to play again press y to play again press n to exit')
if again == 'n':
break #here it says it is outside the loop
elif again != 'y':
print 'oops i don\'t know what you mean plz enter y to play again or n to exit'
else:
continue #this is outside loop as well
The else: continue is unnecessary because you are at the end of the loop.
However, this only asks the question once, and you probably want this in a while loop. You also don't need to check the again == "y" in the outer while loop, because you are controlling the flow here:
while True:
[snip]
again = raw_input("would you like to play again press y to play again press n to exit")
while again not in ('y', 'n'):
again = raw_input("oops i don't know what you mean plz enter y to play again or n to exit")
if again == 'n':
break
I would recommend against using a bare input() because any code could be executed, receiving a string and casting to an int would be safe (and you probably do some error checking):
usergues = int(raw_input("your guess?"))
Putting it all together it looks like:
def main():
while True:
print "guess a number between 1 - 10."
nummer = random.randint(1,10)
found = False
while not found:
usergues = int(raw_input("your guess?"))
if usergues == nummer:
print 'You're the man'
found = True
else:
print 'Too bad dude try again'
again = raw_input('would you like to play again press y to play again press n to exit')
while again not in ('y', 'n'):
again = raw_input('oops i don\'t know what you mean plz enter y to play again or n to exit')
if again == 'n':
break
main()

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