在Python 3.6的数字猜谜游戏中挣扎

时间:2017-01-01 14:03:56

标签: python-3.x

我创建了一个数字猜谜游戏,即代码:

#Guess the number game

import random

guesses = 6
number = random.randint(0, 100)
win = False

while guesses > 0:
    guess = int(input("Guess: "))

    guesses -= 1

    if guess > number:
        print("Your guess is too high", guesses, "remaining")
    elif guess < number:
        print("Your guess is too low", guesses, "remaining")
    elif guess - number < 6:
        print("You are very close")
    else:
        print("Congrats, you guessed")
        win = True
        guesses = 0

if win == False:
    print("Sorry, you didn't guess the number", number)

但是,我想要它,以便如果用户输入的数字比随机数(数字变量)大5或更低5,则打印“你很接近”。

1 个答案:

答案 0 :(得分:0)

怎么样:

import random    
guesses = 6
number = random.randint(0, 100)
win = False

while guesses > 0:
    guess = int(input("Guess: "))

    guesses -= 1

    if guess == number:
        win = True
        guesses = 0
    elif abs(guess - number) < 6: 
        print("You are very close")
    elif guess > number:
        print("Your guess is too high", guesses, "remaining")
    elif guess < number:
        print("Your guess is too low", guesses, "remaining")

if win == False:
    print("Sorry, you didn't guess the number", number)
else:
    print("Congrats, you guessed correct")

如果数字接近(在guess > number检查之前),您需要提前检查;并且abs可以接受两个方向的差异

永远无法联系您guess - number < 6;上述两个条件中的一个已经满足;没有abs这个条件即使对于非常小的猜测也是如此。

如果找到解决方案,也许最好使用for循环和break循环猜测。