首页 > 解决方案 > 关于密码python游戏的问题

问题描述

我想知道我的代码发生了什么,因为如果我们找到了密码,我想在最后打印出来,但我每次都得到它。

import random

answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""

#Game Loop( the body of the loop inside)
while user_winner != True:
    #User input
    guess = input("Can you guess a number between 1 and 100? ")

    #Check The user Input
    try:
        guess_number = int(guess)
    except:
        print("You should write a number!")
        quit()

    #Increase attempt count
    attempts += 1

    #check the user answer against the secret number
    if guess_number == answer:
        user_winner = True
    elif guess_number > answer:
        print("The number is Smaller!!")
    else:
        print("The number is Bigger!!")

    #Get the spelling of the "attempt" word
    if attempts == 1:
        attempt_word = " attempt"
    else:
        attempt_word = " attempts"

    #Display the result
    print("Congratulations!! You did it in " + str(attempts) + attempt_word)

除非我们得到正确的结果,否则我们不应该看到它(打印)

标签: pythonnumbers

解决方案


如果您尝试从上到下模拟循环中的代码,您会看到最后print一行总是在最后读取,因为没有什么可以阻止它到达该点。您将想要将其包裹在一个条件(例如if/else)周围:

if user_winner == True:
    print( "Congratulations!! You did it in " + str( attempts ) + attempt_word )

您还可以考虑将该行放在您编写print的已经存在的语句下:if

if guess_number == answer:
    print( "Congratulations!! You did it in " + str( attempts ) + attempt_word )
elif ...

但是,由于 Python 从上到下读取它,您还需要移动处理attempt_word变量的代码块。


推荐阅读