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

如何在函数内实现循环:输入错误时重新执行货币转换

修正后的货币转换函数代码

以下是实现你需求的修正代码,当用户输入错误货币类型时会重新执行流程,允许再次输入:

def moneyConversion():
    while True:
        print("You can convert dollars to either pounds, euros, or yen")
        convert_to = input("What currency do you want to convert to? ").lower()
        
        # 校验货币类型是否合法
        if convert_to not in ["pounds", "euros", "yen"]:
            print("You must pick either pounds, euros, or yen")
            continue
        
        # 处理金额输入,确保输入为有效数字
        try:
            amount = float(input("How much would you like to convert? "))
        except ValueError:
            print("Please enter a valid number for the amount.")
            continue
        
        # 执行货币转换计算
        if convert_to == "pounds":
            converted_amount = amount * 0.65
        elif convert_to == "euros":
            converted_amount = amount * 1.03
        else:
            converted_amount = amount * 145.73
        
        # 输出转换结果
        print(f"${amount:.2f} US dollars equals {converted_amount:.2f} {convert_to}")
        break  # 转换完成后退出循环

if __name__ == '__main__':
    moneyConversion()

关键修改说明

  • 循环逻辑调整:将整个输入和转换流程放入while True循环,当输入错误时通过continue回到循环起点,实现"从头重新执行"的效果
  • 货币类型校验前置:先判断输入的货币是否合法,不合法直接提示并重新输入,避免无效的金额输入操作
  • 金额输入鲁棒性:添加try-except捕获非数字输入的异常,防止程序崩溃
  • 计算逻辑优化:使用单独的converted_amount存储转换结果,避免修改原始金额导致的重复计算问题
  • 输出格式优化:用格式化字符串保留两位小数,让结果更符合货币显示习惯
  • 修复函数调用错误:原代码调用未定义的main(),改为调用正确的moneyConversion()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:01:18