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

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?.

Related

How can I use str.partition with a text file to split a question and answer for a quiz

I am trying to make a quiz which uses an external text file. The textfile looks like:
Are apples green?TRUE
Are pears green?TRUE
etc etc
I have used x.partition("?")[0]) to split between the question mark so question is to the left and answer to the right.
When I run the program however, the answer doesn't seem to match the csAnswer and I'm not sure why.
I have tried csAnswer.rstrip but it still outputs 'incorrect'.
How can I amend this?
def csQuestions():
for x in questionFile:
print(x.partition("?")[0])
answer = input("Input answer, TRUE OR FALSE: ")
csAnswer = (x.partition("?")[2])
csAnswer.rstrip("\n")
print("cs is ",csAnswer,"answer input is ",answer)
if answer == csAnswer:
print("correct answer")
elif answer !=csAnswer:
print("incorrect")
Try like this (Use .strip() and assign to the variable):
def csQuestions():
for x in questionFile:
que,ans = x.split("?")
print(que)
answer = input("Input answer, TRUE OR FALSE: ")
csAnswer = ans
csAnswer = csAnswer.strip()
print("cs is ",csAnswer,"answer input is ",answer)
if answer == csAnswer:
print("correct answer")
elif answer != csAnswer:
print("incorrect")
To be honest, I wouldn't do it with partition, I would modify the text file so that it is Are apples green?"TRUE so that we can use the split method like this:
for questionandanswer in questionFile:
question = questionandanswer.split('"')[0]
answer = questionandanswer.split('"')[1]
When running your code the code got confused with spaces, etc, now that wouldnt happen anymore. I reccomend using this(its ur code but modified for .split):
questionFile = open(r'C:\Users\incan\OneDrive\Documentos\Code\try.txt', 'r')
def csQuestions():
for x in questionFile:
print(x.split('"')[0])
answer = input("Input answer, TRUE OR FALSE: ")
csAnswer = x.split('"')[1]
csAnswer.rstrip("\n")
print("cs is ",csAnswer,"answer input is ",answer)
if answer == csAnswer:
print("correct answer")
elif answer !=csAnswer:
print("incorrect")
csQuestions()

While loop exceeds max number attempts (3) when asking for an answer

In my program it's supposed to ask the user a question and give them 3 chances to guess the correct answer. But my "while" loop seems to give the user a 4th chance to answer the question and bypassing the "max_attempts" variable.
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 4
while answer != 'Madison':
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
else:
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
All the above answers are correct, just adding a slightly different variant.
print('Quiz program!\n')
attempt = 1
max_attempts = 4
while attempt < max_attempts:
attempt += 1
answer = input('What is the capital of Wisconsin? ')
if answer == 'Madison':
print("Correct!")
break
else:
print('You got it wrong, please try again.\n')
print("Thanks for playing. It took you %s attempt(s)." %(attempt-1))
You have max_attempts = 4 - change that to 3.
You should check if the counter attempt attempt is equal to max_attempts at the beginning of the loop, before you increment the counter again, and you should set max_attempt to 3 instead:
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 3
while answer != 'Madison':
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
else:
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
The problem is with your condition. It should be
attempt < max_attempts:
I also tried implementing it in a more readable way
def main():
introduction()
attempt=1
while attemptValid(attempt) and answerIsWrong(askQuestion(), attempt):
attempt += 1
def attemptValid(attempt):
max_attempts=4
if attempt < max_attempts:
return 1
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
return 0
def answerIsWrong(answer, attempt):
if answer != 'Madison':
return 1
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
return 0
def introduction():
print('Quiz program!\n')
def askQuestion():
return input('What is the capital of Wisconsin? ')
main()
Surely, by adjusting the variable max_attempts to 2, 3, 4, 5 you will eventually find the right number to give you the correct behaviour. But I believe it is more important to know how to think of this issue. I would suggest to think in terms of loop invariants: Make up a condition that is always true in the loop and enforce it while you write the loop. In this case, let's make the value of attempt and the number of time of input() calls equal, and see if your loop is right:
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 4
So your attempt set to 1 after input(). This part is OK, and satisfied the invariant (even it is before the loop). Then the loop:
while answer != 'Madison':
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
You increment attempt, then print, then call input(). I will put the attempt line right after input() call to be consistent with the code above but either case, at right before the if statement, we still have value of attempt equals to number of times we called input(). That is why you have this behaviour.
Now on how to change your code: you now knows what is "invariant" in the loop. You have to decide (1) when to do the check of attempt == max_attempts and (2) what is the right value of max_attempts to check. Other people's answer already gave you the solution.

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

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()

Does raw_input() stop an infinite while loop?

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 ?

Categories

Resources