0

I was wondering if there was a way to store a function in a variable that includes a variable that has not yet been defined, and place that variable that holds the function in after the variable in the function has been defined. For example, I want this script below (this script is an example of the problem I am having in another script, yet the other script is way too long to include here) to print a number of days after you enter in weeks, however I get a NameError: name 'days_weeks' is not defined .

weeks = int(input("Enter a number of weeks"))
def print_weeks():
    print("that is %s days" % days_weeks)
x = print_weeks
def find_days():
    days_weeks = weeks * 7
    x
    x()
find_days()

Now, obviously, I can just plug print_weeks in find_days; however for the project I am working on I am using the first function (print_weeks in this case) dozens of times in my script, and the function is hundred of lines of code long, so I want to keep the function stored in a variable to make things way less sloppy. I have also tried to make days_week a global variable, yet the outcome of the code has stayed the same (or I just did it wrong). I have read a lot of other threads yet I have not been able to find an answer. Sorry if this has been confusing, but basically if anyone has a way to keep print_weeks in a variable and have this script print the days correctly it would be greatly appreciated.

1
  • x = print_weeks is unnecessary. Just use print_weeks where you would use x. Commented Feb 1, 2016 at 13:28

1 Answer 1

1

You're getting the NameError because days_weeks is local to the function find_days, and not accessible to print_weeks. If you want days_weeks to be global, you need to change the find_days function.

def find_days():
    global days_weeks 
    days_weeks = weeks * 7
    x   
    x() 

But, in general, it's better to pass the variables in an out of your functions, rather than rely on globals. In that case your code would look something like this:

def print_weeks(days):
    print("that is %s days" % days)
x = print_weeks

def find_days(f, Nweeks):
    days_weeks = Nweeks * 7
    f(days_weeks)

weeks = int(input("Enter a number of weeks"))
find_days(x,weeks)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.