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
相关产品推荐
相关产品推荐

