Guess-the-Number游戏过早给出答案

时间:2017-02-19 17:51:37

标签: python

我正在学习Python的介绍,但我遇到了一个问题。

请看一下我的剧本:

import random
secretNumber = random.randint(1,20)
print (' I am thinking of a number between 1 and 20.')

#ask the player to guess 6 times.
for guessesTaken in range (1,7):
    print ('take a guess.')
    guess = int(input())

    if guess < secretNumber:
        print ('your guess is too low')
    elif guess > secretNumber:
        print ('your guess is too high')
    else:
        break

    if guess == secretNumber:
        print ('good job! you guessed my number in ' + str(guessesTaken) + ' guesses!')
    else:
        print ('nope. the number i was thinking of was ' + str(secretNumber))

我正在尝试猜猜数字游戏。当我运行脚本时,它会问我:

  1. 猜数字

  2. 当我输入号码时,它会自动给我存储的号码而不是给我6次尝试。

  3. 如果我不清楚任何步骤,请告诉我,我会尽力在下次回答更清晰的问题!

2 个答案:

答案 0 :(得分:0)

if guess == secretNumber:开头的最后一部分是循环的一部分,但您不希望在循环期间给出最终结果。而是将它放在循环之后(在它之外),这意味着你应该减少这4行代码的缩进:

import random
secretNumber = random.randint(1,20)
print (' I am thinking of a number between 1 and 20.')

#ask the player to guess 6 times.
for guessesTaken in range (1,7):
    print ('take a guess.')
    guess = int(input())

    if guess < secretNumber:
        print ('your guess is too low')
    elif guess > secretNumber:
        print ('your guess is too high')
    else:
        break

if guess == secretNumber:
    print ('good job! you guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
    print ('nope. the number i was thinking of was ' + str(secretNumber))

答案 1 :(得分:0)

最简单的解决方案是,如上所述,只需将最后一个if语句移出循环。您正在使用的语法(除了错误的缩进)非常好,这是python的一个很好的开始。但是,在python 3中,你不需要在循环内的if语句中使用else。实际上,如果满足ELSE条件你不需要做任何事情,你可以把它拿出来。