2021年3月23日星期二

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?

https://stackoverflow.com/questions/66736064/use-user-input-or-calculated-value-within-function March 22, 2021 at 02:28AM

没有评论:

发表评论