为什么我的程序在这里给我一个错误?
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中使用Tries ++?是不是有自动增量代码?
编辑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 :(得分:3)
在你的最后一行中,将string
替换为str
- 这应该照顾python抱怨的错误,至少。
答案 1 :(得分: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)