This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I'm quite new to coding. I've managed to produce this code which is a little test for children. It works fine I just need to prevent kids from entering letters or other characters when math questions are asked. Something like "please only enter numbers" should come up. I've tried a variety of functions like ValueError but with no luck. Any help will be appreciated!
import time
import random
import math
import operator as op
def test():
number1 = random.randint(1, 10)
number2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correctResult = operation(number1, number2)
print ("What is {} {} {}?".format(number1, rand_key, number2))
userAnswer= int(input("Your answer: "))
if userAnswer != correctResult:
print ("Incorrect. The right answer is {}".format(correctResult))
return False
else:
print("Correct!")
return True
username=input("What is your name?")
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
while True:
try:
# try to convert the user's input to an integer
usersClass = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
# oh no!, the user didn't give us something that could be converted
# to an int!
print("Please enter a number!")
else:
# Ok, we have an integer... is it 1, 2, or 3?
if usersClass not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
# the input was 1,2, or 3! break out of the infinite while...
break
input("Press Enter to Start...")
start = time.time()
correctAnswers = 0
numQuestions = 10
for i in range(numQuestions):
if test():
correctAnswers +=1
print("{}: You got {}/{} {} correct.".format(username, correctAnswers, numQuestions,
'question' if (correctAnswers==1) else 'questions'))
end = time.time()
etime = end - start
timeTaken = round(etime)
print ("You completed the quiz in {} seconds.".format(timeTaken))
if usersClass == 1:
with open("class1.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
elif usersClass == 2:
with open("class2.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
elif usersClass == 3:
with open("class3.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter an integer value!")
Look, in your code:
import operator as op
# DEFINE THE `get_int` FUNCTION HERE
# (in global scope so other functions can call it)
def test():
then use it below:
userAnswer = get_int("Your answer: ") # call the function
# No ValueErrors!
Related
I am trying to use the variables user_ans_a, user_ans_s, user_ans_m and user_ans_d inside of my game as questions randomly chosen by python. My dilemma is coming from matching the randomly chosen variable to an answer coresponding to that variable. I want the user to be able to enter an anser to those questions.
import random
import re
while True:
score = 0
top = "--- Mathematics Game ---"
print(len(top) * "━")
print(top)
print(len(top) * "━")
print(" Type 'Play' to play")
start_condition = "Play" or "play"
def checkint(input_value):
while True:
try:
x = int(input(input_value))
except ValueError:
print("That was a bad input")
else:
return x
while True:
inp = input()
if inp == "Play":
break
else:
print("Try again")
if inp == "Play":
print("What's your name?")
name = input()
print(f"Hello {name}")
while True:
try:
no_of_rounds = int(input("how many rounds do you want to play? "))
break
except ValueError:
print('Please enter a number.')
for i in range(no_of_rounds):
ran_int1 = (random.randint(1,10))
ran_int2 = (random.randint(1,10))
answer_a = (ran_int1 + ran_int2)
answer_s = (ran_int1 - ran_int2)
answer_m = (ran_int1 * ran_int2)
answer_d = (ran_int1 / ran_int2)
user_ans_a = (f"What does {ran_int1} + {ran_int2} = ")
user_ans_s = (f"What does {ran_int1} - {ran_int2} = ")
user_ans_m = (f"What does {ran_int1} * {ran_int2} = ")
user_ans_d = (f"What does {ran_int1} / {ran_int2} = ")
if checkint(user_ans_a) == int(answer_a):
print(f"That was correct {name}.")
score = score+1
else:
print(f"Wrong {name}, the answer was {answer_a}, try again")
print(f"Score was {score}")
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break
I create a simple code in Phyton, it demands two numbers and until are given you´re in a loop (because the code checks if an int number is given). After that, you have to choose a certain operation. But my code can´t break the loop. I don´t know what´s wrong, if it is the indentation? If I shouldn't use a loop in this, the syntax?
dataRight = False
#Check if the data are int numbers
while not dataRight:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
try:
dataParsec = int(dataParsec)
except:
dataParsec = "Error1"
dataLight = input("LightYear Númber: ")
try:
dataLight = int(dataLight)
except:
dataLight = "Error2"
if dataParsec != "Error1" and dataLight != "Error2":
dataRight = True
#After the data given is right, choose the operation to make.
question = input("Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: ")
question = question.upper()
lightYear = 3.26156
if question == "A":
convertlightYear = dataParsec / lightYear
print("Convert to Parsecs: ", str(convertlightYear))
elif question == "B":
convertParsec = dataParsec * lightYear
print("Convert to LightYear: ", str(convertParsec))
else:
print("Data entered is wrong")
Can someone help me? It's been days and I can´t see what´s wrong.
Code:
As far as I understood, your problem is non-terminating while loop. It's just because of indentation.
while not dataRight:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
try:
dataParsec = int(dataParsec)
except:
dataParsec = "Error1"
dataLight = input("LightYear Númber: ")
try:
dataLight = int(dataLight)
except:
dataLight = "Error2"
# This must be outside the except that's all
if dataParsec != "Error1" and dataLight != "Error2":
dataRight = True
Output:
Convert LightYears and Parsecs, enter the data:
Parsecs Number: l
LightYear Númber: 5
Convert LightYears and Parsecs, enter the data:
Parsecs Number: 2
LightYear Númber: 5
Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: A
Convert to Parsecs: 0.613203497712751
If you want it to stay in the loop until the user enters a number, try something along these lines
dataParsec = input("Parsecs Number: ")
while dataParsec.isdigit() == False:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
This do the work:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
while dataParsec.isdigit() == False:
dataParsec = input("Parsecs Number: ")
dataLightYear = input("LightYears Number: ")
while dataLightYear.isdigit() == False:
dataLightYear = input("LightYears Number: ")
question = input("Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: ")
question = question.upper()
lightYear = 3.26156
if question == "A":
convertlightYear = int(dataParsec) / int(dataLightYear)
print("Convert to Parsecs: ", str(convertlightYear))
elif question == "B":
convertParsec = int(dataParsec) * int(dataLightYear)
print("Convert to LightYear: ", str(convertParsec))
else:
print("Data entered is wrong")
Thanks Blckknght, Bibhav and Victor_G. All of you were of great Help! :D
for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
Hi, I am trying to create a vocabulary test on python. My code works up until this chunk. After the program prompts the user for their guess, the program will say it is incorrect even if it is the right answer. Is there an error in this code? How can I get around this?
This is what it looks like:
English: white
Spanish: blanco
Incorrect
English: purple
Spanish: morado
Incorrect
Thanks!
Full Code:
def main():
import random
wrongAnswers = []
print("Hello, Welcome to the Spanish-English vocabulary test.")
print(" ")
print("\nAfter the test, this program will create a file of the incorrect answers for you to view")
print("\nTo start, please select from the following options: \nverbs.txt \nadjectives.txt \ncolors.txt \nschool.txt \nplaces.txt") #sk
while True: #SK
selection = input("Insert your selection: ").lower() #user inputs selection #sk
if selection == "verbs.txt" or selection == "adjectives.txt" or selection == 'colors.txt' or selection == 'school.txt' or selection == 'places.txt':
print("You have chosen", selection, "to be tested on.")
break
if False:
print("try again.")
selection = input("Insert your selection: ").lower()
break
file = open(selection, 'r')
dictionary = {}
with file as f:
for line in f:
items = line.rstrip("\n").split(",")
key, values = items[0], items[1:]
dictionary[key] = values
length = len(dictionary)
print(length,'entries found')
n= int(input("How many words would you like to be tested on: "))
while n > length:
print("Invalid. There are only" ,length, "entries")
n= int(input("How many words would you like to be tested on: "))
print("You have chosen to be tested on",n, "words.\n")
for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
if len(wrongAnswers) > 0:
wrong = str(wrongAnswers)
output = input("Please name the file you would like you wrong answers to be saved in: ")
outf = open(output, 'w')
outf.write(wrong)
outf.close()
else:
print("You got all of the problems correct!")
main()
I'm writing a Python math game in which the program asks an addition question and the user has to get the right answer to continue. My question is, how can I make the program generate a new math problem when the user gets the last one correct?
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 (True) :
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print("Wrong\n")
userAnswer = int(input("Your answer : "))
input("\n\n Press to exit")
Implement the game with a pair of nested loops. In the outer loop, generate a new arithmetic problem. In the inner loop, keep asking the user for guesses until he either gives the right answer or decides to quit by entering a blank line.
import random
playing = True
while playing:
# Generate a new arithmetic problem.
a = random.randint(1, 50)
b = random.randint(1, 50)
solution = a + b
print('\nWhat is %d + %d? (to quit, enter nothing)' % (a, b))
# Keep reading input until the reply is empty (to quit) or the right answer.
while True:
reply = input()
if reply.strip() == '':
playing = False
break
if int(reply) == solution:
print('Correct. Good job!')
break
else:
print('Wrong. Try again.')
print('Thank you for playing. Goodbye!')
This should get you started. The getnumbers() returns two random numbers, just like in your script. Now just add in you game code. Let me know if you have questions!
import random
def getnumbers():
a = random.randint(1, 50)
b = random.randint(1, 50)
return a, b
print("Math Game!")
while True:
a, b = getnumbers()
# game code goes here
print("%d %d" % (a, b))
input()
This might do what you want:
import random
def make_game():
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (True) :
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print("Wrong\n")
userAnswer = int(input("Your answer : "))
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
while True:
make_game()
end = input('\n\n Press to "end" to exit or "enter" to continue: ')
if end.strip() == 'end':
break
def multiply(): #starts sub program when 'multiply()' is called
num1 = random.randint(1,12) #randomly generates a number between 1 and 12
num2 = random.randint(1,12)
while loop == True: #creates loop, and uses previously defined 'loop'
ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? ")) #asks question and requires a user input
correct = (ans == num1 * num2)
if correct:
print("You are correct! ")
break #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
else:
print("Wrong, please try again. ")
loop == False #if the answer is wrong, it loops back to when 'loop' was last 'True'
I am wondering if there is a way for me to include a line of code that allows me to display "That is not an option!" when a symbol other than a number is entered into the 5th line in the code.
Use an exception to catch unexpected inputs.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
def multiply():
# Randomly generates a number between 1 and 12
num1 = random.randint(1,12)
num2 = random.randint(1,12)
while True:
i = input("What is the answer to {} x {} ".format(
str(num1), str(num2)))
try:
ans = int(i)
except ValueError:
print('That is not an option!')
continue
if ans == num1 * num2:
print("You are correct!")
break
else:
print("Wrong, please try again.")
if __name__ == "__main__":
multiply()
When you convert to int there is the chance that they will enter a non-integer value so the conversion will fail, so you can use a try/except
def multiply(): #starts sub program when 'multiply()' is called
num1 = random.randint(1,12) #randomly generates a number between 1 and 12
num2 = random.randint(1,12)
while loop == True: #creates loop, and uses previously defined 'loop'
try:
ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? ")) #asks question and requires a user input
correct = (ans == num1 * num2)
if correct:
print("You are correct! ")
break #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
else:
print("Wrong, please try again. ")
loop == False
except ValueError:
print("That is not an option")
Note that your previous code is now nested in a try block. If the int() fails because they entered a bad input, it will throw a ValueError that you can catch and notify them.
As a side note, another way to format your question to them would be
'What is the answer to {} x {}?'.format(num1, num2)
This is a nice way to generate a string with injected variable values.