我的下一个任务是修改当前代码。在之前的练习中,我已经编写了一个基本的应用程序,它涵盖了一个数字猜测游戏。守则如下:
# 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.")我的任务是对此进行修改,以便在向用户发送失败消息之前有一定数量的so。到目前为止,这一章已经涵盖了"if,elif,else,for,循环,避免无限循环“。因此,我只想限制我对这些概念的反应。For循环将在下一章中讨论。
我试过什么?
到目前为止,我已经尝试在另一个while循环中使用5 to和to变量来修改这个块,但是它似乎不起作用。
# 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.发布于 2013-03-01 16:08:10
问题在于您的break语句没有缩进以包含在elif中。
elif guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break因此,循环总是在第一次迭代之后停止。缩进要包含在break中的elif,它应该可以工作。
发布于 2013-03-01 16:10:11
中断不在条件中。在它之前添加一个选项卡。
https://stackoverflow.com/questions/15161908
复制相似问题