我的输入如何不等于答案? [英] How does my input not equal the answer?
问题描述
从Unity JS切换到Python一点点,一些更好的观点让我想知道为什么这不起作用。
我最好的猜测是变量 guess
实际上是一个字符串,所以字符串5与整数5不同?
这是发生了什么,以及如何解决这个问题。
Switching from Unity JS to Python for a bit, and some of the finer points elude me as to why this does not work.
My best guess is that the variable guess
is actually a string, so string 5 is not the same as integer 5?
Is this what is happening and either way how does one go about fixing this.
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
guess = input("")
if guess == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())
推荐答案
我假设您使用的是python3。
I am assuming you are using python3.
您的代码唯一的问题是你从输入的值input()
是一个字符串而不是整数。所以你需要转换它。
The only problem with your code is that the value you get from input()
is a string and not a integer. So you need to convert that.
string_input = input('Question?')
try:
integer_input = int(string_input)
except ValueError:
print('Please enter a valid number')
现在您输入为整数,您可以将其与 a
Now you have the input as a integer and you can compare it to a
进行比较代码:
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
# you get the user input, it will be a string. eg: "5"
guess = input("")
# now you need to get the integer
# the user can input everything but we cant convert everything to an integer so we use a try/except
try:
integer_input = int(guess)
except ValueError:
# if the user input was "this is a text" it would not be a valid number so the exception part is executed
print('Please enter a valid number')
# if the code in a function comes to a return it will end the function
return
if integer_input == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())
这篇关于我的输入如何不等于答案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!