关于自制猜数游戏的问题

Question regarding a self made number guessing game

我从 2 天开始就在努力学习 python,我正在通过这个网站上的这个 python 小项目挑战自己:https://www.upgrad.com/blog/python-projects-ideas-topics-beginners/#1_Mad_Libs_Generator

我现在在玩第二个游戏(猜数字游戏)

指令如下:

'''编写一个程序,让计算机在1到10、1到100或1到100之间随机选择一个数字 任何范围。然后给用户一个猜数字的提示。每次用户猜错, 他得到了另一条线索,他的分数被降低了。线索可以是倍数,可以整除, 更大或更小,或所有的组合。 您还需要函数将输入的数字与猜测的数字进行比较,以计算 两者之间的差异,并检查是否在此 python 项目中输入了实际数字。'''

import random

print("Welcome to the number game. A random number will be generated and you can guess which one it is.")
print("You got three tries.")

number = random.randint(1, 99)
guess = ""  # var to store users guess
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess != number and not out_of_guesses:
    if guess_count < guess_limit:
        guess = int(input("Enter a guess: "))
        guess_count += 1
        if guess < number:
            print("Your guess is too small. Try again.")
        elif guess > number:
            print("Your guess is too high. Try again.")
    else:
        out_of_guesses = True

if out_of_guesses:
    print("You are out of guesses. You loose!")
else:
    print("Your guess is correct. You Won!")

输出如下所示:

Welcome to the number game. A random number will be generated and you can guess which one it is.
You got three tries.
Enter a guess: 78
Your guess is too high. Try again.
Enter a guess: 28
Your guess is too small. Try again.
Enter a guess: 29
**Your guess is too small. Try again.**
You are out of guesses. You loose!

我的问题是标记为 strong 的行。其实,用户进入第三次尝试后,没有猜出正确答案,我不想显示“你猜的太...”这句话。但是,在用户尝试结束之前,我确实希望显示它。

关于如何调整代码,您有什么提示吗?

此外,我确实理解了 try 和 except 的概念,但真的不知道将它添加到哪里才能使游戏在输入错误的输入类型时更加“流畅”。

亲切的问候

鉴于当前的代码结构,您可以通过在 guessnumber 比较中添加额外的检查来避免打印最后一次猜测的提示。

关于异常处理,程序的崩溃点涉及用户输入与数字的比较。在用户输入的整数转换周围添加异常处理似乎是合适的。在递增 guess_countcontinue 以允许另一个用户输入之前执行此操作将允许游戏 运行 进行 3 次有效输入。

用于引用异常的 _ 变量是一个 'throwaway' 变量 - 这只是一个约定俗成的名称。然而,在解释会话中,_ 将存储先前执行的语句的 return 值。

import random

print("Welcome to the number game. A random number will be generated and you can guess which one it is.")
print("You got three tries.")

number = random.randint(1, 99)
guess = ""  # var to store users guess
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess != number and not out_of_guesses:
    if guess_count < guess_limit:
        try:
            guess = int(input("Enter a guess: "))
        except ValueError as _:
            print('Wrong input type')
            continue
        guess_count += 1
        if guess < number and guess_count != guess_limit:
            print("Your guess is too small. Try again.")
        elif guess > number and guess_count != guess_limit:
            print("Your guess is too high. Try again.")
    else:
        out_of_guesses = True

if out_of_guesses:
    print("You are out of guesses. You lose!")
else:
    print("Your guess is correct. You Won!")