NameError:未定义名称“April”

时间:2014-02-05 17:43:40

标签: python

我知道这是愚蠢的,但我无法弄清楚为什么它不起作用。请帮忙。

def main():
    yourAge=getAge() #get subject's age
    yourWeight=getWeight() #get subject's weight 
    yourBirthMonth=getMonth() #get subject's birth month
    correctAnswers(getAge, getWeight, getMonth)

def getAge():
    yourAge=input('Enter your age. ')
    return yourAge

def getWeight():
    yourWeight=input('Enter your weight.')
    return yourWeight

def getMonth():
    yourBirthMonth=input('Enter your birth month. ')
    return yourBirthMonth

def correctAnswers(getAge, getWeight, getMonth):
    if getAge <= 25:
        print'Congratulations, age is less than 25.'

    if getWeight >= 128:
        print'Congratulations, weight is more than 128.'

    if getMonth == 'April':
        print'Congratulations, month is April.'

main()

追溯:

 Traceback (most recent call last):
  File "C:/Users/Beth/Documents/jeff/prog/lab 03/lab 3-5.py", line 35, in <module>
    main()
  File "C:/Users/Beth/Documents/jeff/prog/lab 03/lab 3-5.py", line 10, in main
    yourBirthMonth=getMonth()#get subject's birth month
  File "C:/Users/Beth/Documents/jeff/prog/lab 03/lab 3-5.py", line 22, in getMonth
    yourBirthMonth=input('Enter your birth month. ')
  File "<string>", line 1, in <module>
NameError: name 'April' is not defined

3 个答案:

答案 0 :(得分:5)

使用raw_input(),而不是input();后者试图将文本输入解释为Python代码。

在这种情况下,键入April被解释为变量名称。您可以输入"April",但最好不要在此使用input()

答案 1 :(得分:1)

在python2 input中评估输入。使用raw_input获取未评估的字符串。

在您的情况下,input尝试在输入变量april后进行查找,但肯定不存在。

要想象效果,请尝试在为该年龄发布时输入1/0


基本上你的功能可能如下所示:

def getAge():
    return int(raw_input('Enter your age. '))

def getWeight():
    return int(raw_input('Enter your weight. '))

def getMonth():
    return raw_input('Enter your birth month. ')

答案 2 :(得分:0)

替换

yourBirthMonth=input('Enter your birth month. ')

yourBirthMonth=raw_input('Enter your birth month. ')

在Python 2中,raw_input()返回一个字符串,input()尝试将输入作为Python表达式运行