我的下一个任务是修改当前代码。在之前的练习中,我编写了一个涵盖数字猜谜游戏的基本应用程序。代码如下: -
# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
# guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit.")
我的任务是对此进行修改,以便在将失败消息提供给用户之前进行有限的运行次数。到目前为止,本章已经涵盖了“if、elif、else、for、循环,避免无限循环”。因此,我只想限制我对这些概念的回应。下一章将介绍 for 循环。
我尝试了什么?
到目前为止,我已经尝试在另一个 while 循环中使用 5 go 和ries 变量来修改块,但它似乎不起作用。
# guessing loop
while tries < 6:
guess = int(input("Take a guess: "))
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
elif guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
tries += 1
input("You didn't do it in time!")
input("\n\nPress the enter key to exit.")
任何指针或突出显示我错过的内容将不胜感激,以及对我错过的任何解释。教自己以编程方式思考也被证明很棘手。
什么不起作用 当我运行它时,循环条件似乎不起作用。我的闲置反馈如下。
这意味着我的问题可以概括为我的循环逻辑在哪里损坏?
>>> ================================ RESTART ================================
>>>
Welcome to 'Guess My Number'!
I'm thinking of a number between 1 and 100.
Try to guess it in as few attempts as possible.
Take a guess: 2
Take a guess: 5
Higher...
You didn't do it in time!
Press the enter key to exit.