Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I have to use a global for imported variable?

import datetime
from datetime import date

def get_one_week():
    global date
    seven_dates = []
    date = date.today()
    for i in range(7):
        date += datetime.timedelta(days=-1)
        date_str = date.strftime('%Y%m%d')
        seven_dates.append(date_str)
    return seven_dates

print(get_one_week())

This will print out:

['20220901', '20220831', '20220830', '20220829', '20220828', '20220827', '20220826']

My question, both ‘date’ and ‘datetime’ are imported variables, but why do I have use a global declaration for the ‘date’ but not for the ‘datetime’ variable?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s because you declared your variable date so python thinks that you referenced the local variable before any assignment try change it to other name so it will use the global one

import datetime
from datetime import date

def get_one_week():
    seven_dates = []
    d = date.today()
    for i in range(7):
        d += datetime.timedelta(days=-1)
        date_str = d.strftime('%Y%m%d')
        seven_dates.append(date_str)
    return seven_dates
    
print(get_one_week())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading