【发布时间】:2018-04-27 12:06:41
【问题描述】:
我一直试图弄清楚如何在函数之间传递数据,我是编码新手。我尝试了多种方法来做到这一点,我很难理解数据是如何传递的,我的代码如下。帮助会很棒。
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任何值——如果你想编写更简洁的代码,你应该从那里开始 -
您没有将参数传递给您的任何函数(所有调用都是空的:
bmi()、math_cal()等)。相反,您正在修改全局变量(在您的脚本中)。
标签: python function pass-by-reference