How to ask a string again if the wrong answer is entered? - python

I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
if answer is '4':
print("Great job!")
elif answer != '4':
print ("Nope! please try again.")
while answer != '4':
print ("What is 2 + 2?")
break

There are a couple of things wrong with your code. Firstly, you are only asking for the answer once at the moment. You need to put answer = input() in a while loop. Secondly, you need to use == instead of is:
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = 0
while answer != '4':
answer = input()
if answer == '4':
print("Great job!")
else:
print ("Nope! please try again.")
There are a number of ways you can arrange this code. This is just one of them

print('Guess 2 + 2: ')
answer = int(input())
while answer != 4:
print('try again')
answer = int(input())
print('congrats!')
I think this is the simplest solution.

By now you've got more answers than you can handle, but here are another couple of subtleties, with notes:
while True: # loop indefinitely until we hit a break...
answer = input('What is 2 + 2 ? ') # ...which allows this line of code to be written just once (the DRY principle of programming: Don't Repeat Yourself)
try:
answer = float(answer) # let's convert to float rather than int so that both '4' and '4.0' are valid answers
except: # we hit this if the user entered some garbage that cannot be interpreted as a number...
pass # ...but don't worry: answer will remain as a string, so it will fail the test on the next line and be considered wrong like anything else
if answer == 4.0:
print("Correct!")
break # this is the only way out of the loop
print("Wrong! Try again...")

You only need the wrong-answer check as loop condition and then output the "great job" message when the loop is over (no if is needed):
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
while answer != '4':
print ("Nope! please try again.")
print ("What is 2 + 2?")
answer = input()
print("Great job!")

Here is my two cents for python2 :
#!/usr/bin/env python
MyName = raw_input("Hello there, what is your name ? ")
print("Nice to meet you " + MyName)
answer = raw_input('What is 2 + 2 ? ')
while answer != '4':
print("Nope ! Please try again")
answer = raw_input('What is 2 + 2 ? ')
print("Great job !")

Related

How do I write a question to play game again?

I'm expanding upon the random number guessing game from Automate the Boring Stuff with Python and I can't figure out how to write the code for when the game asks if you want to play again.
More specifically, if the user types "yes" or "no" to wanting to play the game, the code does the appropriate thing. However, if the user types in anything else, I want it to say "Please answer yes or no" and then allow the user to enter another answer.
In this case, my code currently prints "Please answer yes or no", but then it treats the answer as "yes", so it starts the game again. I don't want it to immediately start a new game unless the user specifically types "yes". How can I do this?
Here's the code
import random
print ('Hello, what is your name?')
name = input ()
name = name.strip()
while True:
print ('Well, ' + name + ', I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
print ('Take a guess.')
for guessesTaken in range (1, 7):
try:
guess = int (input ())
if (guess < secretNumber and guessesTaken < 6):
print ('Your guess is too low. Guess again.')
elif (guess > secretNumber and guessesTaken < 6):
print ('Your guess is too high. Guess again.')
else:
break # This condition is for the correct guess
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print ('Sorry. Your guesses were all wrong. The number I was thinking of was ' + str(secretNumber))
print ('Would you like to play again?')
answer = input ()
answer = answer.lower()
if answer == 'no':
print ('Ok.')
break
elif answer == 'yes':
print ('Ok, let\'s go!')
else:
print ('Please answer yes or no')
Simply have a second loop that will continue to prompt until a valid input is given.
usr_response = input('Would you like to play again: ').lower()
while usr_response not in ('yes','no'):
usr_response = input('Invalid response. Please choose yes or no: ')
if usr_response == 'no':
break
So the problem is that the code checks for valid input only once. If the 2nd input is invalid as well, no condition is checked. For the solution, You should replace:
if answer == 'no':
print ('Ok.')
break
elif answer == 'yes':
print ('Ok, let\'s go!')
else:
print ('Please answer yes or no')
with:
list1 = ['yes', 'no']
while answer not in list1:
print ('Please answer yes or no:')
answer = input()
if answer == 'no':
print ('Ok.')
break
elif answer == 'yes':
print ('Ok, let\'s go!')

How do I stop this from repeating?

I am new to coding. It works alright until you guess a number. then it says either higher or lower eternally. Please help me understand what I've done wrong. I have tried searching the internet and trying to retype some of the code but it won't work. I am trying to make a conversation as well as a mini guess the number game.
Here's my Code
# Conversation A
import random
print("Answer all questions with 'yes' or 'no' and press ENTER")
print('Hello I am Jim the computer')
z = input('How are you? ')
if z == 'Good' or z == 'Great' or z == 'good' or z == 'great':
print("That's great!")
else:
print("Oh. That's sad. I hope you feel better.")
a = input("what's your name? ")
print(a + "? Thats a nice name.")
b = input('Do you own any pets? ')
if b == 'yes' or b == 'Yes':
print("That's cool. I love pets!")
else:
print("That's a shame, you should get a pet. ")
c = input("Do you like animals? ")
if c == 'yes' or c == 'Yes':
print("Great! Me too!")
else:
print("Oh that's sad. They're really cute. ")
d = input("Do you want to see a magic trick? ")
if d == "yes" or d == "Yes":
input("Ok! Think of a number between 1-30. Do you have it? ")
print("Double that number.")
print("Add ten.")
print("Now divide by 2...")
print("And subtract your original number!")
y = input("Was your answer 5? ")
if y == 'yes' or y == 'Yes':
print("Yay i got it right! I hope you like my magic trick.")
else:
print("Oh that's sad. I'll work on it. I really like magic tricks and games.")
else:
print("Ok. Maybe next time. I love magic tricks and games!")
e = input("Do you want to play a game with me? ")
if e == "yes" or e == "Yes":
randnum = random.randint(1,100)
print("I am thinking of a number between 1 and 100...")
if e == 'no' or e == 'No':
print("oh well see you next time" + a + '.')
guess = int(input())
while guess is not randnum:
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
if guess < randnum:
print("Higher.")
if guess > randnum:
print("Lower.")
You need to add a break statement when you want stop looping and move the input for guess inside the loop so you don't exit before printing the statement:
while True:
guess = int(input())
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
break
Edit: Also, you dont want to use is every time: Is there a difference between "==" and "is"?

print something when input isn't something specified

Sorry for the horrible question. Basically, I am making the Yes or No game in Python and I need it to print something e.g. "You Win" if they input something from a library that I have already made with every acceptable word. TY in advance
q1 = input ("Answer: ")
while q1 == "yes" or "Yes" or "no" or "No":
print ("Sorry but you answered \"" + q1 + "\" which means you lose!")
sys.exit ("\nGame Over")
if q1 == ###:
print ("Well done you have earned yourself a point")
score +=1
print ("Your current score is: " + score)
input_word = input('Insert a word: ')
list_of_acceptable_words = ['word1', 'word2']
if input_word in list_of_acceptable_words:
print('You Win')
Where input_word is a string containing the input from the user and list_of_acceptable_words is a list of acceptable words
You can probably start out from this snippet, using the built-in set type:
>>> lib={'Alice','Bob'}
>>> print('Bob' in lib)
True
>>> print('Carol' in lib)
False
Then one can add a bit of code around to match your needs more closely:
>>> guess='Dave'
>>> print(['You lose...', 'You WIN!'][guess in lib])
You lose...
>>> guess='Alice'
>>> print(['You lose...', 'You WIN!'][guess in lib])
You WIN!
Edit: now that you have updated your OP with some snippet, I can write some code more in line with your needs.
accepted=set(line.strip() for line in open('accepted.txt'))
q1 = input("Answer: ")
while q1.lower() in {"yes", "no"}:
print ("Sorry but you answered \"" + q1 + "\" which means you lose!")
sys.exit ("\nGame Over")
if q1 in accepted:
print ("Well done you have earned yourself a point")
score +=1
print ("Your current score is: " + score)
Of course, if you count good answers, you will want to put this into some loop, then the initializition of accepted can stay outside.

My python code does not run a print statement at the end of a loop

I have this problem when i run the program it all goes good an all, but when a user gets the right answer, the code does not print neither print("Good Job!") or print("Correct"). what is wrong with the code ?
import random
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (userAnswer != result) :
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
input("\n\n Press to exit")
The problem is that your while-loop will only run as long as the first answer is wrong. Everything that is indented after while (userAnswer != result) will be ignored by Python if the first answer is right. So logically a first correct answer can never reach print("Correct"), since that would require the answer to be both wrong (to start the while loop) and right (to get to "Correct").
One option is to get rid of the while-loop, and just use if's. You get two chances this way, then you lose.
if (userAnswer == result):
print("Well done!")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
else:
print("Nope all wrong you lose")
Another option is to make an infinite loop using While. (like #csharpcoder said)
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In the last option a wrong answer gets "Wrong answer" and the while-loop starts again, since True is of course still True. So you try again, until you get the right answer, which will bring you to "correct, good job" and then break (which stops the loop).
I struggled with while-loops and kind of getting it in my head that indentation means Python will treat it as 'one thing' and skip it all if I start it with something that's False.
If the answer is correct, then
while (userAnswer != result) :
will cause the loop contents to be skipped.
First of all, you get input outside of your loop and then don't do anything with it. If your answer is correct on the first try, you will get no output because userAnswer != result will be False immediately and your while loop won't run.
Some other points:
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
is redundant because you are guaranteed to fall into one of these, as you will only get here if the answer is wrong (and therefore > or < result). Just print "Wrong" without a condition, as the only reason this would run is if the answer was wrong.
print("Correct")
print("Good Job!")
You can use \n to print on a new line instead of having multiple print statements together. Usually you only use multiple prints together for readability, but print("Correct\nGood job!") isn't that much less readable.
if (userAnswer == result):
#...
break
You don't need break here because the answer is already correct and the loop won't repeat anyway.
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
Here, you append string literals to string literals ("Hello!" + " "). You don't need to do that as you can just write "Hello! ".
result = firstNumber + secondNumber
result = int(result)
The result (pun not intended) is already an integer, so you don't need to convert it.
How about using a infinite while loop something like this :
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In your logic if you enter the wrong answer first time and correct answer afterwards , then it will work as per your requirement , but if you enter the correct answer first time it will simple skip the while loop .
I played around a bit to refactor, in an attempt to make it more clear:
import random
name = input("Hello ! What's your name? ")
print("Hello, {name}!".format(name=name))
print("Ok, {name}, let's start!".format(name=name))
first_number = random.randint(1, 50)
second_number = random.randint(1, 50)
correct_answer = first_number + second_number
print("What is, '{first} + {second}'?".format(first=first_number,
second=second_number))
user_answer = None
while user_answer != correct_answer:
try:
user_answer = int(input("Your answer : ")) # ValueError will be raised if non integer value given
except ValueError:
print("Invalid Input!")
user_answer = None
if user_answer:
if user_answer == correct_answer:
print("Correct")
print("Good Job!")
else:
print('--> Wrong, try again!')
input("\n<< Press any key to exit >>")

Improving Code - Python [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
This code works but is not as efficent as possible. Can you tell me how to make it more efficent? I belevie there is away to not have so many functions but I have forgotten how. The script is a multi choose quiz. I have defined each question as a new function. Is this the best way to do this?
def firstq (): # 1st Question
global q1list,answer1
q1list = ["Wellington","Auckland","Motueka","Masterton"]
q1count = 0
print ("Question 1")
print ("From which of the following Towns is the suburb NEWLANDS located?")
while q1count < 4:
print (q1count," ",q1list[q1count])
q1count = q1count + 1
answer1 = int(input("What number answer do you choose?"))
if answer1 == 0: print ("Correct answer!")
elif answer1 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def secq (): #Second Question
global q2list,answer2 # Makes answer2 and q2list avalible anywhere on the page.
q2list = ["Wellington","Christchurch","Pairoa","Dunedin"] # List of answers to choose from.
q2count = 0 # defines what the q2 count is. SEE BELOW
print ("Question 2")# prints "question 2"
print ("What NZ town is known for L&P?") # Prints the question
while q2count < 4:
print (q2count," ",q2list[q2count]) # Whilst the number of answers (q2list) is below 4 it will print the next answer.
q2count = q2count + 1
answer2 = int(input("What number answer do you choose?")) # asks for answer
if answer2 == 2: print ("Correct answer!") # If answer is correct, prints "Correct answer"
elif answer2 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.") # If answer is correct, prints "Sorry! Incorrect Answer. Better luck with the next Question."
print("Next Question below:") # prints "Next Question
# these provide spacing!
print(" ")
print(" ")
def thrq ():
global q3list,answer3
q3list = ["Lewis Carroll","J.K. Rowling","Louis Carroll","Other"]
q3count = 0
print ("Question 3")
print ("Who wrote the book Alice In Wonderland?")
while q3count < 4:
print (q3count," ",q3list[q3count])
q3count = q3count + 1
answer3 = int(input("What number answer do you choose?"))
if answer3 == 0: print ("Correct answer!")
elif answer3 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def fouq ():
global q4list,answer4
q4list = ["WA","DC","WD","WC"]
q4count = 0
print ("Question 4")
print ("What is the abbreviation for Washington?")
while q4count < 4:
print (q4count," ",q4list[q4count])
q4count = q4count + 1
answer4 = int(input("What number answer do you choose?"))
if answer4 == 1: print ("Correct answer!")
elif answer4 != 1: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def fivq ():
global q5list,answer5
q5list = ["Yes","No, they're found around New Zealand","No","No, they're found around the UK"]
q5count = 0
print ("Question 5")
print ("Are walruses found in the South Pole?")
while q5count < 4:
print (q5count," ",q5list[q5count])
q5count = q5count + 1
answer5 = int(input("What number answer do you choose?"))
if answer5 == 2: print ("Correct answer!")
elif answer5 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def sixq ():
global q6list,answer6
q6list = ["G.M.","General M's","G Motors","Grand Motors"]
q6count = 0
print ("Question 6")
print ("What is the other name for General Motors?")
while q6count < 4:
print (q6count," ",q6list[q6count])
q6count = q6count + 1
answer6 = int(input("What number answer do you choose?"))
if answer6 == 0: print ("Correct answer!")
elif answer6 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def sevq ():
global q7list,answer7
q7list = ["Greece","USA","Egypt","Italy"]
q7count = 0
print ("Question 7")
print ("Which of the following countries were cats most honored in?")
while q7count < 4:
print (q7count," ",q7list[q7count])
q7count = q7count + 1
answer7 = int(input("What number answer do you choose?"))
if answer7 == 2: print ("Correct answer!")
elif answer7 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def eigq ():
global q8list,answer8
q8list = ["I find","I see","I presume","I am"]
q8count = 0
print ("Question 8")
print ("Complete this phrase-Dr. Livingstone,")
while q8count < 4:
print (q8count," ",q8list[q8count])
q8count = q8count + 1
answer8 = int(input("What number answer do you choose?"))
if answer8 == 2: print ("Correct answer!")
elif answer8 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print(" ")
print(" ")
def end():
if answer1 == 0 and answer2 == 2 and answer3 == 0 and answer4 ==1 and answer5 ==2 and answer6 ==0 and answer7 == 2 and answer8 == 2: print("YAY, all questions correct! You have won the 1 million!")
else: print("Sorry you have some incorrect questions! You have not won any money! :(") # If all answers are correct, this will display YAY, all questions correct! You have won the 1 million! If not it will print Sorry you have some incorrect questions! You have not won any money! :(.
def printorder ():
# Defines ther order that it will be printed in
firstq()
secq()
thrq()
fouq()
fivq()
sixq()
sevq()
eigq()
end()
name = l" " # while name is blank it will continue
while name != "quit": #While the name is not quit it will continue. If name is quit it will stop.
print ("The $1,000,000 Quiz! Can you win the 1 Million?")#Prints Welcome Message
name = input("Lets Get Started! What is your name: ")# asks for name
if name == "quit":
break # if the name is quit it will stop if not....
printorder()# ....prints printorder
This is just a pointer.
Instead of
def sixq():
global q6list, answer6
...
create a function
def question(qlist, qanswer):
...
and pass in qlist and qanswer as parameters, much of the code is duplicated and can be eliminated this way. And you also eliminate the use of globals at the same time. You can return whatever value(s) you need to the calling code at the end of this function using return. (note that Python allows you to return more than one value)
Adjust above as needed, ie if you need to supply another parameter etc. Essentially you want to factor out duplicate code into a single function, and provide the necessary parameters for what makes it unique.
Finally, using a single function in place of eight, will making maintaining your code much easier. If you find a problem with your code, or simply want to change something, you'll only have to correct it in one place, rather than in 8 different functions .. this is a major benefit.

Categories