2014-02-05 62 views
0

我知道這是愚蠢的,但我不明白爲什麼它不起作用。請幫忙。NameError:name'April'is not defined

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 
+0

這是蟒2.7或3.x? – IanAuld

回答

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. ') 
5

使用raw_input(),不input();後者試圖將文本輸入解釋爲Python代碼。

在這種情況下,鍵入April被解釋爲變量名稱。您可以輸入"April",但最好不要在此處使用input()

0

替換

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

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

在Python 2,的raw_input()返回一個字符串,並輸入()嘗試運行輸入作爲Python表達式