Subroutine not working, error message saying variable is not defined

自闭症网瘾萝莉.ら 提交于 2019-12-25 04:29:06

问题


i am using a subroutine and i think it is the cause of my problem, here is my code :

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

The variable month is just 01,02,03,04,05,06,07,08,09,10,11,12

The error message is : File "C:/Users/Akshay Patel/Documents/TASK 2/task two month dob.py", line 13, in if dob == ['30','31'] :

NameError: name 'dob' is not defined


回答1:


The variable dob is local to sub1 and hence you cannot see it at global scope.

You might want to return it:

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

I personally would refactor your code a bit:

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

If at some moment you want to input a whole date, you can consider using this:

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)


来源:https://stackoverflow.com/questions/22052625/subroutine-not-working-error-message-saying-variable-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!