You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中如何为多参数函数获取用户输入并返回计算结果

现有代码的问题

  • 调用object_distance()时没有传入必填的f、di两个参数,运行会直接报参数缺失错误
  • input()的作用是接收用户输入的字符串,你把计算函数放在input()的括号里,只会把函数返回值当成输入提示文本,完全达不到传参计算的目的
  • input()默认返回字符串类型,不能直接代入数值公式做运算,需要先转换为浮点类型

正确实现代码

def object_distance(f, di):
    do = 1 / ((1 / f) - (1 / di))
    return do

# 依次获取两个参数的用户输入并转换为浮点型
f = float(input("请输入焦距f(单位:cm):"))
di = float(input("请输入像距di(单位:cm):"))

# 传入参数调用函数得到计算结果
odistance = object_distance(f, di)

print("The object distance is: {0:3.1f} cm".format(odistance))

可选优化(非必须)

如果需要避免用户输入非数字内容导致程序崩溃,可以加简单的输入校验逻辑:

def get_float_input(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("输入无效,请输入数字")

def object_distance(f, di):
    do = 1 / ((1 / f) - (1 / di))
    return do

f = get_float_input("请输入焦距f(单位:cm):")
di = get_float_input("请输入像距di(单位:cm):")
odistance = object_distance(f, di)
print("The object distance is: {0:3.1f} cm".format(odistance))

内容的提问来源于stack exchange,提问作者thatscoolman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:45:05