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

Python统计奇偶个数程序列表首元素自动丢失问题咨询

问题原因

首次输入的整数没有存入列表是代码逻辑顺序错误导致的,具体问题出在while循环的执行流程:

  • 你在循环外第一次调用input()拿到了用户输入的第一个值(也就是示例中的1),存储到number变量中
  • 进入while循环后,第一行代码就再次调用input()获取新的输入,直接覆盖了之前存的第一个输入值,没有把第一个值添加到ev_od_list里,就导致首元素丢失
  • 最终你添加到列表里的第一个元素是第二次输入的2,同时最后输入的结束标记0也被误加入了列表。

修正后的代码

把while循环的逻辑调整为先添加当前值到列表,再读取下一次输入即可,同时因为调整后0不会进入列表,不需要额外执行移除0的操作:

ev_od_list = []
even = []
odd = []

number = int(input("Enter an integer(entering 0 would end the process): "))

while number != 0:
    # 先把当前合法值加入列表,再读取下一个输入
    ev_od_list.append(number)
    number = int(input("Enter an integer(entering 0 would end the process): "))

for i in ev_od_list:
    if i % 2 == 0:
        even.append(i)

print("The number of even numbers you entered is:", len(even))

for j in ev_od_list:
    if j % 2 != 0:
        odd.append(j)       

print(ev_od_list)
print("The number of odd numbers you entered is:", len(odd))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:12:03