简体   繁体   中英

Use user input or calculated value within function

Say I define a function:

def calculate_bmi(height):
    bmi = weight / (height)**2
    print('BMI:',bmi)

I have saved this as functions.py in the same folder as the file for the code where I call this function. I am using jupyter notebook for the main code.

The variable weight is calculated in the main code, and not known to the user calling the function. Hence, it cannot be given as an input parameter.

So, when the function is called in the main code:

import functions
from functions import calculate_bmi

weight = calculate_weight() # weight is calculated 
calculate_bmi(2)

I get the following error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-c66651ccce8b> in <module>
      2 from functions import bmi
      3 weight = calculate_weight() # weight is calculated 
----> 4 calculate_bmi(2)

D:\PP\functions.py in calculate_bmi(height)
     75 
     76 def calculate_bmi(height):
---> 77     bmi = weight / (height)**2
     78     print('BMI:',bmi)

NameError: name 'weight' is not defined

Is there a way to make python use the values already calculated earlier in the code, within the function as they are already stored in it's memory?

You need to pass weight as a variable to your function, ie

weight = calculate_weight()  
## weight = input('Input weight:') - for user input

def calculate_bmi(height, weight):
    bmi = weight / (height)**2  
    return bmi

bmi = calculate_bmi(5, weight)
print('BMI:',bmi)

Also, name your functions with respect to what they do, not the variables they produce.

In Python, an imported function can't access the variables of the module it's called in. Its access ends at the module where it's defined . You might have been confused by the term "global scope", since it's not really "global", it's module scope.

The best way to solve this problem is to make weight a parameter, as @crusher083 recommended in their answer , but FYI, it's possible to edit variables in the global scope of an imported module. For example:

import functions

functions.weight = 215
functions.calculate_bmi(2)  # -> BMI: 53.75

This is probably a bad idea in this case, but this technique is useful for monkey-patching modules that you can't edit yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM