【问题标题】:IF statement will only consider ELIF? [duplicate]IF语句只会考虑ELIF吗? [复制]
【发布时间】:2018-09-15 14:07:44
【问题描述】:

怎么了?我正在玩我的学校策划项目,最近才开始涉足 Python - 我遇到了一个我根本无法弄清楚的问题?我看过其他人的问题,他们似乎和我有同样的问题,但似乎更有选择性,我的代码有点不同。谁能告诉我为什么每当我回答这个问题时,它会立即跳到“再试一次!”,即使我知道事实 rnumber == tnumber? (使用 Python 3.4.2)。

#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = input("Guess the four digit number. ")
type(tnumber)
#Compares their number to the random number
if tnumber == rnumber:
    print ("You win!")
elif rnumber != tnumber:
    print ("Try again!")
    numot = numot+1

【问题讨论】:

  • 你在用type(tnumber)做什么?
  • tnumber 是一个 string...rnumber 是一个 integer...它们永远不会相等...你需要首先转换您的输入:tnumber = int(tnumber)...
  • 啊,我明白了,谢谢!
  • 顺便说一句,这里不需要elif。一个简单的else 就可以了。

标签: python python-3.x


【解决方案1】:

您需要将输入设为 int,以便将其视为数字,试试这个

#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = int(input("Guess the four digit number. "))
#Compares their number to the random number
if tnumber == rnumber:
    print ("You win!")
else rnumber != tnumber:
    print ("Try again!")
    numot = numot+1

【讨论】:

    猜你喜欢
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 2014-11-19
    • 2014-05-13
    • 2014-05-30
    • 2017-07-03
    相关资源
    最近更新 更多