Python Forum

Full Version: function error: undefined variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
This is my first def function and i cannot figure out why i get a, Nameerror: name 'mpg' is not defined. Any help is much appreciated!!. Smile

#!/usr/bin/env python3
def calculateMPG(milesDriven,gallonsUsed):
    mpg=milesDriven/gallonsUsed
    mpg=round(mpg,1)
    return mpg

def main():
    choice='y'
    while choice.lower()=='y':
        #get input form user
        milesDriven=float(input('enter miles driven'))
        gallonsUsed=float(input('enter gallons used'))
        #call MPG function
        calculateMPG(milesDriven,gallonsUsed)
        print('miles per gallon:\t',mpg)
        #determine fate of loop
        choice=input('do you want to continue: y/n')
mpg is assigned on line 2, so it's in scope for calculateMPG(). But I don't see that it's assigned anywhere in main(). To be used there, it needs to be assigned in that function (a local), or in an enclosing scope (such as a global). As it's not found there, it's undefined when you reach line 15.
Ah yes!
#!/usr/bin/env python3
def calculateMPG(milesDriven,gallonsUsed):
    mpg=milesDriven/gallonsUsed
    mpg=round(mpg,1)
    return mpg

def main():
    choice='y'
    while choice.lower()=='y':
        #get input form user
        milesDriven=float(input('enter miles driven'))
        gallonsUsed=float(input('enter gallons used'))
        mpg=calculateMPG(milesDriven,gallonsUsed)
        print(mpg)
        #determine fate of loop
        choice=input('do you want to continue: y/n')

Thank you very much. But can you tell me why it didn't work when I tried to set mpg=0 local within the def main().
Depends on what else was happening. It should have removed the specific error, but mpg would have just been zero. You'd need to post the code and tell what you expected to happen and how that differed from what actually did happen.