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

Python中for循环无法累加所有符合条件输入值的问题咨询

问题原因及修复方案

你的代码问题出在缩进错误——if语句没有包含在for循环的代码块里。循环结束后,程序只会用最后一次输入的question和included值来判断是否累加,所以只能得到最后一次符合条件的数值。

修改后的代码

total = 0 

for i in range(5):
    question = int(input("Enter a number : "))
    included = input("Do you want that number included , (y/n) : ")
    # 将if语句缩进,纳入for循环的执行逻辑中
    if included.lower() == "y":
        total += question

print(total)

额外优化说明

  • 用included.lower() == "y"可以同时匹配大写Y和小写y,比写两个或判断更简洁。
  • 缩进后,每次循环都会执行if判断,只要用户输入y/Y,就会把当前输入的数值累加到total中,实现多次累加的效果。
  • total += question是total = total + question的简写,Python中常用这种方式简化累加操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 04:26:55