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

如何按条件控制输入提示显示 解决Python计算器第三个数输入提前弹出问题

问题定位
  • 第三个数的输入语句写在了条件判断外部,程序顺序执行时无论用户输入Y/N都会触发该提示
  • 原有代码存在两处错误:N分支的求和逻辑错误包含了未使用的num3,且语句末尾缺失右括号
修复后的代码
num1 = float(input("Enter a number: "))
num2 = float(input("Enter a second number: "))
question = input("Would you like to add another number? Y/N ")

if question == "Y":
    # 仅当用户选择Y时才触发第三个数的输入请求
    num3 = float(input("Enter a third number: "))
    print(num1 + num2 + num3)
elif question == "N": 
    print(num1 + num2)
可选优化

可以对用户输入做兼容处理,支持大小写、多余空格的输入场景:

num1 = float(input("Enter a number: "))
num2 = float(input("Enter a second number: "))
# 去除输入首尾空格后转大写,兼容y/n、带空格的输入
question = input("Would you like to add another number? Y/N ").strip().upper()

if question == "Y":
    num3 = float(input("Enter a third number: "))
    print(num1 + num2 + num3)
elif question == "N": 
    print(num1 + num2)
else:
    print("输入无效,请输入Y或N")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 18:39:04