【问题标题】:How to user input while defining function?定义功能时如何用户输入?
【发布时间】:2016-02-12 17:11:08
【问题描述】:

我想计算长方体的面积。我试过这个功能:

def area(l, b, h):
    return l*b*h

但我想提示用户输入类似的值

lx = float(input("Enter Length"))

如何定义这个函数?

【问题讨论】:

  • 你的意思是像:def area(): return float(input("Enter Length: "))*float(input("Enter Length: "))*float(input("Enter Length: "))?

标签: python python-2.7 python-3.x


【解决方案1】:

你已经有了 2/3 的答案。 你做的第一件事就是“定义”函数。现在您只需要使用用户输入的值“调用”它。我假设您还希望用户定义 base 和 height 变量。

# Define function
def area(l, b, h):
    return l*b*h

# Take user input
lx = float(input("Enter Length"))
bx = float(input("Enter Base"))
hx = float(input("Enter Height"))

# Call function with user input
a = area(lx, bx, hx)

# Display results to user
print(a)

您也可以在函数本身内部请求输入,并在 print 语句中调用该函数:

# Define function
def area():
    # Take user input
    lx = float(input("Enter Length"))
    bx = float(input("Enter Base"))
    hx = float(input("Enter Height"))
    return lx*bx*hx

# Call function and display results to user
print(area())

为了获得额外奖励,您可能需要check 确认用户输入有效(例如,他们输入的不是字母而是数字)。

【讨论】:

    猜你喜欢
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 2019-03-29
    相关资源
    最近更新 更多