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

使用Python函数参数做输入值乘法实现单位转换运行异常求助

问题修复说明

核心问题列表

  • 变量作用域混淆:顶部定义的全局变量和main函数内的局部变量同名,inches_to_smoots函数读取的是值为0的全局变量,导致运算结果始终和初始值一致。
  • 输入类型错误:input()返回值默认是字符串,未转换为数值类型无法正常做数学运算。
  • 函数逻辑错误:inches_to_smoots的入参未被使用,且转换逻辑写反了乘法和除法,单位转换应该用总英寸数除以单单位对应英寸数,才能得到自定义单位的数值。
  • 输出取值错误:打印语句调用的是全局inches变量,没有使用函数返回的计算结果answer。
  • 语法规范问题:函数定义前的多余缩进、不必要的str()包裹,都会引发潜在报错。

额外问题解答

你注释里问的「在input语句里输出变量」可以用f-string实现,格式为input(f"包含{变量名}的提示文本")。

修复后可运行代码

# 单位转换函数
def inches_to_custom_unit(item_length_inch, unit_per_inch):
    # 输入参数:物品总英寸数、单个自定义单位对应的英寸数
    custom_unit_value = item_length_inch / unit_per_inch
    return custom_unit_value

def main():
    unit = input("What is the name of your unit? ")
    # 把输入转成float数值类型支持小数运算
    unit_value = float(input("What is the length of your unit in inches? "))
    item = input("What is the name of the object you'd like to convert to your unit? ")
    # 用f-string在input提示里插入item变量
    item_length = float(input(f"What is the length of {item} in inches? "))
                             
    answer = inches_to_custom_unit(item_length, unit_value)
                             
    # 打印计算结果
    print(f"{item_length} inches is {round(answer,2)} {unit}s!")
                            
if __name__ == "__main__":
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:57:02