【发布时间】:2017-12-22 21:07:11
【问题描述】:
我是 python 的早期初学者,需要一些帮助。游戏的重点是猜测一个数字,如果它不正确,numguesses 加 1。我知道代码效率不高,但我需要它用于项目。代码如下:
import random
from datetime import datetime
answer = random.randint(1, 2)
guess = 0
now = datetime.now()
play = 'y'
print 'Welcome to Hi-Lo'
print 'The current time is: ' '%s-%s-%s' % (now.year, now.month, now.day)
while play != 'n':
while guess != answer:
guess = int(input('Pick a number inbewteen 1-100 to see if its higher or lower:'))
if guess == answer:
numguesses = numguesses + 1
print 'You are correct! The number was: ' + str(answer)
print 'It took ' + str(numguesses) + ' guess(es)'
elif guess > answer:
print 'Too high'
else:
print 'Too low'
play = str(input('Play again? [y/n]?'))
它产生的错误是:
Traceback (most recent call last):
File "C:-----------------------------.py", line 17, in <module>
numguesses = numguesses() + 1
NameError: name 'numguesses' 未定义
因此,如果有人可以对此提供简单的解释,我将不胜感激。谢谢!
【问题讨论】:
-
numguesses从来没有初始值,那怎么加1呢?在while循环之前,您需要numguesses = 0。 -
错误信息与脚本中的行不匹配。为什么
numguesses后面有()? -
while play != 'n'的正文还需要缩进 -
如果您刚开始使用 Python,并且在 Windows 上,为了您的理智,请立即安装 Python 3!