2014-02-26 54 views
0

我使用一個子程序,我認爲這是我的問題的原因,這裏是我的代碼:子程序還沒有工作,錯誤消息說變量沒有定義

def sub1(): 
    dob=input('Please enter the date of the person (dd) : ') 
    while dob not in ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']: 
     print('you have entered an incorrect day') 
     dob=input('Please enter the date of the person (dd) : ') 
sub1() 
if month == '02' : 
    if dob == ['30','31'] : 
     print('You have entered incorrecty') 
     sub1() 

變量一個月就是01,02 ,03,04,05,06,07,08,09,10,11,12

錯誤消息是: 文件「C:/ Users/Akshay Patel/Documents/TASK 2/task two month dob。 py「,第13行,在 if dob == ['30','31']:

NameError:name'dob'is not defined

+2

修復你的縮進......它在Python中有所不同。您的錯誤信息會使您的原始來源中的縮進無誤。 ''dob''只在''sub1''中定義,所以當你在''sub1''之外使用它時,它不在 – Wolf

回答

2

變量dob位於sub1的本地,因此在全局範圍內無法看到它。

你可能想退貨:如果在某一時刻,你想輸入一個整體

def inputDay (month): 
    #february doesn't respect leap years 
    maxDay = [42, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] [month] 
    dob = 0 
    while dob > maxDay or dob < 1: 
     dob = int(input('Please enter day of month: ')) 
    return dob 

month = 2 #change this value accordingly 
day = inputDay(month) 
print('{}/{}'.format(month, day)) 

def sub1(): 
    dob=input('Please enter the date of the person (dd) : ') 
    while dob not in ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']: 
     print('you have entered an incorrect day') 
     dob=input('Please enter the date of the person (dd) : ') 
    return dob ########### 
dob = sub1() ######## 
if month == '02' : 
    if dob in ['30','31'] : ######### in not == 
     print('You have entered incorrecty') 
     dob = sub1() ############## 

我個人重構你的代碼位日期,你可以考慮使用這個:

from datetime import datetime 

def inputDate(): 
    while True: 
     try: return datetime.strptime(input('Enter date (m/d/yyyy): '), '%m/%d/%Y') 
     except ValueError: pass 

a = inputDate() 
print(a.day, a.month, a.year) 
+0

那麼我該怎麼做? – ap306

+0

@ ap306查看我答案的其餘部分。 – Hyperboreus

+0

還需要縮進while循環 – advert2013