【发布时间】:2021-03-18 05:01:59
【问题描述】:
我从 2 天开始就在尝试学习 python,我正在通过这个网站上的这个小 python 项目挑战自己:https://www.upgrad.com/blog/python-projects-ideas-topics-beginners/#1_Mad_Libs_Generator
我现在在第二场比赛(猜数字游戏)。
指令如下:
'''制作一个程序,其中计算机随机选择一个介于 1 到 10、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 的概念,但真的不知道在哪里添加它以使游戏在输入错误的输入类型时更加“流畅”。
亲切的问候
【问题讨论】:
标签: loops if-statement random numbers