我的输入怎么和答案不一样呢?
- 2025-04-15 09:21:00
- admin 原创
- 29
问题描述:
我从 Unity JS 切换到 Python 一段时间了,但有些细节问题我还是不明白为什么它不起作用。我猜测这个变量guess
实际上是一个字符串,所以字符串 5 和整数 5 不一样?这是怎么回事?无论如何,该如何解决这个问题?
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 {} {} {}?
".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())
解决方案 1:
我假设你正在使用 python3。
你的代码唯一的问题是你获取的值input()
是一个字符串而不是整数。所以你需要转换它。
string_input = input('Question?')
try:
integer_input = int(string_input)
except ValueError:
print('Please enter a valid number')
现在,您输入的是整数,您可以将其与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 {} {} {}?
".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())
解决方案 2:
是的,你说得完全正确,这"5"
与 不同5
。你可以5
使用 将其转换为字符串str(5)
。另一种方法是"5"
使用 将其转换为整数,int("5")
但这种方法可能会失败,因此最好处理异常。
因此,您的程序的更改可能如下所示:
if guess == str(a):
而不是:
if guess == a:
另一种选择是将猜测值转换为整数,如另一个答案中解释的那样。
编辑:这仅适用于 Python 版本 2.x:
但是,您使用的是input()
,而不是raw_input()
。input()
如果您输入的是整数,它会返回一个整数(如果您输入的文本不是有效的Python表达式,则会失败)。我测试了您的程序,它询问What is 4 - 2?
;我输入了2
,它说 ,Correct!
所以我不明白您的问题是什么。
你有没有注意到,如果你的程序询问What is 9 - 4?
你是否可以输入9 - 4
,它却说Correct!
?那是因为你使用了input()
,而不是raw_input()
。同样,如果你输入,例如c
,你的程序会失败,并显示NameError
不过,我会使用raw_input()
并将答案与str(correct_answer)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD