从另一个函数调用python数组项

时间:2016-03-12 23:41:39

标签: python arrays date-arithmetic

我希望从两个日期获得天数;第一个存储在一个函数的数组中,然后使用一些算术的天数,但是我得到了无效的语法和NameError“未定义”其他地方。我做错了什么?

def registration():
    global reg_date, names, numbers, airtime, registration_details
    reg_date = datetime.date.today()
    names = raw_input("Names ")
    numbers = raw_input("Numbers ")   
    airtime = int(raw_input("Enter Airtime: "))
registration_details = [reg_date, names, numbers, airtime] # Store Registration Details

def status():
    global registration_details
    current_date = datetime.date.today()  # the current date may be x days since registration
    reg_date = registration_details[0] # the date of registration stored in the array during registration   
    days_since_registration = current_date – reg_date
    print  days_since_registration.days
registration()

1 个答案:

答案 0 :(得分:2)

您可以采取一些措施来保持变量和函数的整齐封装,同时避免NameError和与范围相关的其他问题。例如,您可以使用函数参数而不是global变量(尽可能避免使用global。这是here的更多信息。其次,您可以将函数放入您实例化的类中,并根据需要进行访问。有关here

的更多信息

也许您的代码应该完全重写,但就目前而言,这是修复NameError同时保留大部分原始代码的一种方法:

import datetime

def registration():
    reg_date = datetime.date.today()
    names = raw_input("Names ")
    numbers = raw_input("Numbers ")   
    airtime = int(raw_input("Enter Airtime: "))
    return [reg_date, names, numbers, airtime]


def status(reg_info_list):
    current_date = datetime.date.today()  # the current date may be x days since registration
    reg_date = reg_info_list[0] # the date of registration stored in the array during registration   
    days_since_registration = current_date - reg_date
    print  days_since_registration.days


registration_details  = registration() # Store Registration Details
status(registration_details)