2013-04-22 50 views
0

這是我編輯過的一個簡單的小猜謎遊戲。我知道應該運行良好,但它不斷給我一個錯誤。在第12行,它表示「unindent不匹配任何外部縮進級別」,箭頭指向「guess = input()」中的右括號。任何幫助?我看不出它有什麼問題!python隨機數字遊戲中的縮進錯誤

# 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) 
+3

用'python -tt my_script'運行它永遠不要混合製表符和空格,並使用一個好的編輯器/ ide – 2013-04-22 17:07:16

+0

那麼這很可能是我的問題。我別無選擇,只能使用在線IDE,它有時候會混淆我的代碼。 – Xiam 2013-04-22 17:19:57

+0

你是什麼意思你別無選擇?如果需要,你可以在記事本中編寫python。 – thegrinner 2013-04-22 17:51:44

回答

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 
+0

仍然給我一個錯誤。它顯示[this](http://i.imgur.com/9VUOYZd.png)。 – Xiam 2013-04-22 17:26:47

+0

@Xiam使用'raw_input()'而不是'input()',因爲在Python 2.7中'input()'實際上將輸入評估爲Python代碼,而不是String。我建議你堅持'raw_input()'。 'raw_input()'返回一個字符串,你也可以將它轉換爲你喜歡的類型(例如''int()')。但是,如果您在Python 3.x中使用'input()',它將工作得很好。 – 2013-04-22 17:58:43

+0

@Xiam所以要解決這個問題,把myName ='input()'改成'myName = raw_input()'。我也注意到,你沒有初始化'guessesTaken'值。我想你可能想在開始while循環之前初始化這個'guessesTaken = 0'。 – 2013-04-22 17:59:36

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使用(),而不是輸入(),「怎麼我使用2.7.3 :)乾杯!

+0

你知道你可以做'x = raw_input(「猜一猜:」)'而不需要額外的提示行嗎? – 2013-04-22 18:07:41

+0

是的,但我想在下一行輸入名稱:) – 2013-04-22 18:11:56