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

Calling python array item from another function

我想得到两个日期的天数;第一个存储在函数的数组中,然后使用天数进行某些算术运算,但我在其他地方得到无效语法和 NameError "not defined"。我做错了什么?

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

您可以采取多种措施来保持变量和函数的整洁封装,同时避免 NameErrors 和其他与范围相关的问题。首先,您可以使用函数参数而不是 global 变量(最好尽可能避免 globals。更多关于 here). Second, you could put your functions into classes that you instantiate and access as needed. More on that 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)