【问题标题】:Python Marking Error? [duplicate]Python标记错误? [复制]
【发布时间】:2016-06-20 13:46:05
【问题描述】:

我对 Python 还是很陌生。在学校,我们必须创建一个数学游戏,而我正在创建一个 9 次桌面游戏。但是,它告诉我答案是不正确的,即使它是正确的?请帮忙!

import random
print(" Hello there!")#prints hello there
print("What is your name?")#asks user for a name
name= input()#sets name to the input
print(name, ", are you ready to test your nine times table? ")#asks user if they are ready to test their 9 times table
print (name, ", here we go!")#prints here we go
print ("Question 1:")#prints Question 1:
number1 = random.randint(1,12)#sets number1 to a random value from 1 to 12
answer= 9*number1#sets answer to 9 times number1
print ("what is 9 times", number1, "?")#asks what is 9 times number 1
if answer==input():
    print ("well done," , name,"thats correct!")
else:
    print("sorry, the correct answer was", answer, )

【问题讨论】:

  • 如果您使用的是 Python 3(看起来很像),这个 if answer==input(): 正在将字符串与数字进行比较。
  • print(" Hello there!")#prints hello there 不要这样做!注释是为了解释程序的不明显之处,而不是为了大声朗读。这种噪音只会让您的代码更难阅读和使用。

标签: python


【解决方案1】:

您的问题是您将字符串 (input()) 与数字 (answer) 进行比较。

您可以通过以下方式解决此问题:

if answer==int(input()):

这会将您的input() 转换为int。作为一个好处,如果用户输入的不是int,它也会引发错误。

这假设您将继续进行整数乘法。如果没有,你可能想看看float()

【讨论】:

  • 类似地,您可以将answer 转换为str,这样如果用户输入了一个非数字,它将被视为不相等而不是引发错误。
  • 虽然是这样,但由于这是一个数学测试,因此获得这种类型的错误更有意义。至少对我来说。然后,您可以给出错误消息,例如“请输入一个数字”,而不仅仅是“不等于”。
  • 我同意,尽管 input() 嵌入在条件中,并且 OP 可能不熟悉 try:except: 我认为这是一个有效的补充点。
猜你喜欢
  • 1970-01-01
  • 2017-05-10
  • 2013-08-05
  • 2012-04-06
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多