Python function question

I wrote a python code and this is it

def calculate_miles_per_gallon(miles_driven,gallons_used):
mpg=miles_driven/gallons_used
mpg=round(mpg,1)
return mpg

miles=500
gallons=14
mpg=calculate_miles_per_gallon(miles,gallons)

but when i run it nothing happen, how can I get out
put from this code??what i have done wrong???

in order to get output, you need to use print().

1 Like

What if you write:
print(calculate_miles_per_gallon(miles,gallons))
instead of
mpg=calculate_miles_per_gallon(miles,gallons)

or if you add
print(mpg)
after mpg=calculate_miles_per_gallon(miles,gallons)

@dev8274201527 if you click the </> icon in the menu bar atop the text box when you post your code, you can make it look like this:

def calculate_miles_per_gallon(miles_driven,gallons_used):
    mpg=miles_driven/gallons_used
    mpg=round(mpg,1)
    return mpg

miles=500
gallons=14
mpg=calculate_miles_per_gallon(miles,gallons)

Isn’t that better?


Actually, when you run it, many things happen:

  • The Python interpreter scans your code line by line, looking for syntax errors.

  • If there are none, it notes in the first line the keyword def , followed by a function name, in turn followed by parentheses containing several variable names (parameters), all of which constitute a function declaration.

  • It stores the indented block of lines following the function declaration (i.e., the function body) in memory for future reference, and assigns that memory address to the function name, calculate_miles_per_gallon, which is kept in another part of memory (the call stack) for quick access.

  • It stores the values 500 and 14 in memory, and assigns those addresses to the variable names miles and gallons, respectively.

  • It sees the line mpg=calculate_miles_per_gallon(miles,gallons), and knows because it has access to the function name calculate_miles_per_gallon, and the variables miles and gallons, that it should bring that previously-stored function to the call stack, and execute it line-by-line, assigning within it the values 500 to the variable miles_driven and 14 to the variable gallons_used, producing a value of 35.714…

  • It assigns that value to the variable mpg.

  • Being done with the function, Python removes it and its variables miles_driven and gallons_used from the call stack.

  • … And then, only if you have, as suggested by @stetim94, added the line print(mpg), it prints 35.714… to the screen.

2 Likes