子程序不起作用,错误消息说变量未定义

时间:2014-02-26 20:33:42

标签: python subroutine

我正在使用子程序,我认为这是我的问题的原因,这是我的代码:

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 /任务两个月dob.py”,第13行,in     如果dob == ['30','31']:

NameError:名称'dob'未定义

1 个答案:

答案 0 :(得分:2)

变量dobsub1的本地变量,因此您无法在全局范围内看到它。

您可能想要退回它:

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() ##############

我个人会稍微重构一下你的代码:

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))

如果您想在某个时刻输入整个日期,可以考虑使用:

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)