我一直在试图弄清楚如何在函数之间传递数据,我不熟悉编码。我已经尝试了多种方式来做到这一点,我很难理解数据是如何传递的,我的代码如下所示。帮助会很棒。
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。因此,我找到了自己的方式,尝试了解如何以更有效的方式重写此代码。我正在寻找一种方法来引用函数来在函数之间传递数据,但是我还没有找到一种干净的方法来执行该过程。
答案 0 :(得分:1)
使用函数时会传递值的位置:
让我们先来看看返回值: 例如,在h()函数中,您要求用户输入高度。该值存储在高度
中height = input("Enter employee's height in inches: ")
检查完所需的所有案例后,您可以使用"返回" 返回函数末尾的一个值。
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(),它将询问高度并返回它获得的值。这可以由你这样的程序使用:
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)
使用变量时。