Question

I've been googling for 30 minutes but I can't find a solution to my problem. Please help!

import math

amount = input("Enter amount of medicine left: ")
dose = input("Enter dose per day: ")

def convertString(str):
    try:
        returnValue = int(str)
    except ValueError:
        returnValue = float(str)
    return returnValue

def count_days(amount, dose):
    last_days = amount / dose
    return last_days

print("Your medicine will run out in ",last_days," days.")

I get this error: NameError: name 'last_days' is not defined

Why isn't this working?

Was it helpful?

Solution

The variable last_days is local within the count_days function. That means that as soon as the function ends, the variable is no longer available. That is however not a problem as the function actually returns that value, making it available for others.

So when you do my_var = count_days(amount, dose), then the function will execute, and return its last_days result which is then stored in my_var.

last_days = count_days(amount, dose)
print("Your medicine will run out in ", last_days, " days.")

OTHER TIPS

last_days is defined just within count_days. Initialise the variable on top of the file to change the visibility

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top