2009-10-05 104 views
2

爲什麼我的程序在這裏給我一個錯誤?運行一個非常簡單的Python程序的問題

import random 

TheNumber = random.randrange(1,200,1) 
NotGuessed = True 
Tries = 0 

GuessedNumber = int(input("Take a guess at the magic number!: "))     

while NotGuessed == True: 
    if GuessedNumber < TheNumber: 
     print("Your guess is a bit too low.") 
     Tries = Tries + 1 
     GuessedNumber = int(input("Take another guess at the magic number!: ")) 

    if GuessedNumber > TheNumber: 
     print("Your guess is a bit too high!") 
     Tries = Tries + 1 
     GuessedNumber = int(input("Take another guess at the magic number!: ")) 

    if GuessedNumber == TheNumber: 
     print("You've guess the number, and it only took you " + string(Tries) + "!") 

錯誤在最後一行。我能做什麼?

編輯:

另外,爲什麼能;噸我用嘗試次數++這裏在Python?沒有自動增量代碼嗎?

編輯2:錯誤是:

Traceback (most recent call last): 
    File "C:/Users/Sergio/Desktop/GuessingGame.py", line 21, in <module> 
    print("You've guess the number, and it only took you " + string(Tries) + "!") 
NameError: name 'string' is not defined 
+0

你有一個無限循環 – SilentGhost 2009-10-05 22:24:50

+0

'string' - >'str' – jfs 2009-10-05 22:28:31

+0

'string'沒有定義:) – OscarRyz 2009-10-05 22:34:54

回答

2

str,不string。但是你的無限循環是一個更大的問題。自動遞增是這樣寫的:

Tries += 1 

一般性意見:你可以提高你稍微的代碼:

the_number = random.randrange(1,200,1) 
tries = 1 

guessed_number = int(input("Take a guess at the magic number!: ")) 
while True: 
    if guessed_number < the_number: 
     print("Your guess is a bit too low.") 

    if guessed_number > the_number: 
     print("Your guess is a bit too high!") 

    if guessed_number == the_number: 
     break 
    else: 
     guessed_number = int(input("Take another guess at the magic number!: ")) 
     tries += 1 

print("You've guessed the number, and it only took you %d tries!" % tries) 
+0

我用你的代碼修復了它,我的電腦在主板上自拍。非常感謝。 – 2009-10-05 22:28:14

+0

你在拍攝前是否修復了無限循環? – foosion 2009-10-05 22:30:59

+0

我的意思是無限循環讓我的電腦自己殺死了xD – 2009-10-05 22:31:42

3

在你的最後一行,與str替換string - 應該採取錯誤的護理至少,python抱怨着。