python随机数游戏中的缩进错误

时间:2013-04-22 17:05:18

标签: python indentation

这是一个我编辑过的简单的小猜谜游戏。我知道应该运行良好,但它一直给我一个错误。在第12行,它表示“unindent与任何外部缩进级别不匹配”,箭头指向“guess = input()”中的右括号。有帮助吗?我看不出它有什么问题!

# This is a guess the number game.
import random

guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')

while guessesTaken < 6:
      print('Take a guess.')
    guess = input()
    guess = int(guess)
    guessesTaken = guessesTaken + 1
    if guess < number:
        print('Your guess is too low.')
    if guess > number:
        print('Your guess is too high.')
    if guess == number:
        break
if guess == number:
    guessesTaken = str(guessesTaken)
    print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + '         guesses!')
if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was ' + number)

2 个答案:

答案 0 :(得分:3)

下面:

while guessesTaken < 6:
      print('Take a guess.')
    guess = input()
    # the rest of the code

print('Take a guess.')行应该有4 spaces indentation。像这样......

while guessesTaken < 6:
    print('Take a guess.')
    guess = input()
    # the rest of the code

答案 1 :(得分:1)

Thanakron Tandavas向您展示了路径,但整个代码以防万一...

# This is a guess the number game.
import random

guessesTaken = 0
myName = raw_input('Hello! What is your name?\n')
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')

while guessesTaken < 6:
    print('Take a guess.')
    guess = input()
    guess = int(guess)
    guessesTaken = guessesTaken + 1
    if guess < number:
        print('Your guess is too low.')
    if guess > number:
        print('Your guess is too high.')
    if guess == number:
        break
if guess == number:
    guessesTaken = str(guessesTaken)
    print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + '         guesses!')
if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was ' + number)

注意我使用raw_input()而不是input(),'因为我使用2.7.3 :)干杯!