在函数之间传递数据

Passing Data between functions

我一直在努力弄清楚如何在函数之间传递数据,我是编码新手。我已经尝试了多种方法来做到这一点,我正在努力理解数据是如何传递的,我的代码如下。帮助会很棒。

x = []
y = []
z = []

def w():   #Welcome greeting the user and asking for their name
    print("Welcome to the BMI Index Calculator.")
    name = input("Enter employee's name or Exit to quit: ")  # Allows the user to input there name as a variable
    if str.isnumeric(name):  # Test as a string
        print("That is not a name.")
        w()
    if name == 'Exit':  # sets the Exit for the program
        print("Exiting program...")
        exit()  # ends program
    else:
        name = x.append(name)

def h():
    height = input("Enter employee's height in inches: ")
    if height == '0':  # sets the Exit for the program
        print("Exiting program...")
        exit()  # ends program
    else:
        height = y.append(height)


def wt():
    weight = input("Enter employee's weight in lbs: ")
    if weight == '0':  # sets the Exit for the program
        print("Exiting program...")
        exit()  # ends program
    else:
        weight = z.append(weight)


def bmi():     #gives the data back to the user
    print(str(x).replace('[', '').replace(']', '').replace("'", '') + "'s " + "BMI profile")
    print("---------------------------")
    print("Height: ", str(y).replace('[', '').replace(']', '').replace("'", ''), '"')
    print("Weight: ", str(z).replace('[', '').replace(']', '').replace("'", ''), "lbs.")


def math_cal():
    bmi_weight = int(z) * 703
    bmi_height = int(y) ** 2
    print("BMI: ", bmi_weight / bmi_height)


def run():
    x = w()
    y = h()
    z = wt()
    xy = bmi()
    xz = math_cal()
    __main__()

run()

__main__()

我已成功将数据传递给其他函数,但代码未能将列表视为 int。因此,我在这里找到了自己的出路,试图了解如何以更有效的方式重写这段代码。我正在寻找一种引用函数以在函数之间传递数据的方法,但是我还没有找到一种干净的方法来执行该过程。

使用函数时有几个值传递点:

  • 在函数的开头,带参数
  • 在函数的最后,作为return值

让我们先来看看return值: 例如,在您的 h() 函数中,您要求用户提供高度。该值存储在 height

height = input("Enter employee's height in inches: ")

检查完你想要的所有情况后,你可以 return 函数末尾的一个值,方法是使用 "return":

return height 

完整的函数变为:

def h():
   height = input("Enter employee's height in inches: ")
   if height == '0':  # sets the Exit for the program
      print("Exiting program...")
      exit()  # ends program
   return height

这意味着如果您调用函数 h() 它将询问高度和 return 它获得的值。这可以被你这样的程序使用:

bmi_height = h() 

bmi_height = h()*2

如果您想将输入的值乘以 2。

第二部分,在函数开头给函数传值,参数为:

比如你想在计算BMI时使用身高和体重,那么函数就变成:

def bmi(height, weight)
    print("BMI: ", bmi_weight / bmi_height)

这个函数必须这样调用:

bmi(170, 85)

输入硬编码值或

height = 170
weight = 85
bmi(height, weight)

当你使用变量时。