Python中的数字游戏

时间:2018-09-04 17:53:18

标签: python-3.x

我开始使用Python,并且尝试制作一个“数字猜谜游戏”。您有6个猜测,介于1和100之间。

程序将告诉您通往高处,向下或关闭的方式。

我的问题是比赛结束。我只能让我的系统传递一条消息。

因此,如果您赢了或输了游戏,则会出现相同的消息。请在下面找到整个内容。感谢您的帮助。

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

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

    guesses -= 1

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

if win == True:
    print("Sorry loser!")
else:
    print("Great. You won. Big deal.")

1 个答案:

答案 0 :(得分:1)

您将win设置为True ,应该在循环开始前将其设置为False

win = False # line 4

尽管,您根本不需要win标志。在Python中,可以使用while-elsefor-else语句。 else仅在不中断循环的情况下才被执行,您可以在那里运行丢失的代码。

使用break摆脱循环比将条件手动设置为虚假状态更自然。

import random
number = random.randint(0, 100)

for guesses in range(6, 0, -1):
    guess = int(input("guess: "))

    if guess == number:
        print("Great. You won. Big deal.")
        break
    elif abs(guess - number) < 4:
        print("You are very close..", guesses - 1, "guesses remaining")
    elif guess > number:
        print("Your guess is too high!", guesses - 1, "guesses remaining")
    elif guess < number:
        print("Your guess is too low!", guesses - 1, "guesses remaining")
else:
    print("Sorry loser!")