我无法弄清楚为什么我遇到这种语法错误。它表示数字未定义,但“数字”设置为“raw_input”。谁能帮我吗?这是代码和错误消息 -
def main():
number = raw_input('I have a number between 1 and 10. Can you guess it? Please type your first guess: ')
guess(number)
def guess(number):
randomNumber = random.randrange(1,10)
correct = False
while not correct:
if number > randomNumber:
print'Too High. Try again.'
elif number < randomNumber:
print'Too Low. Try again.'
elif number == randomNumber:
print'Correct!'
playAgain = raw_input('Excellent! You guessed the number! Would you like to play again (y or n)? ')
if playAgain == 'y':
main()
Traceback (most recent call last):
File "<pyshell#48>", line 2, in <module>
if number > randomNumber:
NameError: name 'number' is not defined
答案 0 :(得分:1)
我不知道您在哪里获得当前错误,因为在尝试运行代码时遇到了不同的语法错误。话虽如此,这里有很多问题,而不仅仅是number
的分配。
在Python中,缩进控制代码中的语句的执行方式。 def
和if
之类的内容必须缩进,否则会导致语法或逻辑错误。
This page words it better than I do.
在您当前的计划中:
def main():
为空
number = raw_input( ...
超出main()
方法
guess(number)
也位于main()
方法
guess()
的大多数都在函数体之外
correct = False
与任何其他缩进级别
此外,即使缩进已修复,您当前的代码也不会多次要求用户输入,并且不会在多个guess()
来电中保持相同的目标号码。 main()
方法也未被调用。
试试这个:
import random
def main():
guess()
def guess():
number = int(raw_input('I have a number between 1 and 10. Can you guess it? Please type your first guess: '))
randomNumber = random.randrange(1,10)
while true:
if number > randomNumber:
print 'Too High. Try again.'
elif number < randomNumber:
print 'Too Low. Try again.'
elif number == randomNumber:
print 'Correct!'
break
number = int(raw_input('I have a number between 1 and 10. Can you guess it? Please type next guess: '))
playAgain = raw_input('Excellent! You guessed the number! Would you like to play again (y or n)? ')
if playAgain == 'y':
main()
main()