2009-10-05 87 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抱怨着。