修改当前代码

时间:2013-03-01 16:06:17

标签: python loops

我的下一个任务是修改当前代码。在之前的练习中,我编写了一个涵盖数字猜谜游戏的基本应用程序。代码如下: -

# 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,loops,avoid infinte loops”。因此,我想限制我对这些概念的回应。 for循环将在下一章介绍。

我尝试了什么?

到目前为止,我已尝试在另一个循环中修改块,使用5循环和尝试变量,但它似乎不起作用。

# 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.

2 个答案:

答案 0 :(得分:2)

问题是您的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中,它应该有效。

答案 1 :(得分:0)

休息不符合条件。 在它之前添加一个标签。