如何打印此elif字符串

时间:2015-09-22 22:38:34

标签: python if-statement

我正在尝试创建一个猜谜游戏,它运作良好。但是,我想要包含一个部分,如果用户将数字放在100以上,则会告诉您,您的选择应该小于100.下面的代码似乎没有这样做。我究竟做错了什么?

import random
comGuess = random.randint(0,100)
while True:
    userGuess = int(input("Enter your guess  :"))
    if userGuess > comGuess:
            print ("Please go lower")
    elif userGuess < comGuess:
            print ("Please go higher")
    elif userGuess > (100):
            print ("Your choice should be less than 100")
    elif userGuess <1:
            print ("Your choice should be less than 100")
    else:
        print ("Great, you got it right")
        break

2 个答案:

答案 0 :(得分:3)

任何高于100的数字肯定会高于目标,并输入if条件。低于1的任何数字肯定会低于目标,并输入第一个elif。如果您想验证用户的输入,您应该之前将其与comGuess进行比较:

if userGuess > (100):
        print ("Your choice should be less than 100")
elif userGuess <1:
        print ("Your choice should be less than 100")
elif userGuess > comGuess:
        print ("Please go lower")
elif userGuess < comGuess:
        print ("Please go higher")    
else:
    print ("Great, you got it right")
    break

答案 1 :(得分:1)

你的第一个if声明正在捕捉大于comGuess的任何,即使它也超过100,所以后来的elif userGuess > (100)永远不会有机会发射。移动elif,或将第一个if语句更改为if (userGuess > comGuess) and (userGuess <= 100)