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

Python列表编程求助:输入数值后无输出问题及代码逻辑疑问

问题分析与解决方案

Hey there! Let's figure out why your code isn't working as expected, then clear up those questions you have about different list operations.

核心错误:无限循环的while语句

The biggest issue in your code is the while loop starting at line 8. Let's break down what happens when you enter an even number:

  • When List[i] % 2 == 0 is true (for even numbers), the loop will keep running forever because List[i] never changes inside the loop. The condition stays true, so your program gets stuck here and never reaches the print statements later.

You only need to check if the number is even once per input, so replace while with if instead. That way, the code runs the even-number logic just once when the condition is met, then moves on to the next input.

修正后的代码

Here's your fixed code with the key change marked, plus an edge-case handling for no even numbers:

List = []
EvenList = []
totalnum = 0
count = 0

for i in range(10):
    List.append(int(input("Enter a number: ")))
    # Changed from while to if
    if List[i] % 2 == 0:
        EvenList.append(List[i])
        totalnum += List[i]
        count += 1

print(EvenList)
# Avoid division by zero if all inputs are odd
if count > 0:
    average = totalnum / count
    print("Average: ", average)
else:
    print("No even numbers entered, average can't be calculated.")

关于你困惑的代码写法差异解释

Let's clear up why your original code changes were necessary:

1. List[i] = int(input(...)) vs List.append(...)

  • When you initialize List = [], it's an empty list with no elements. Trying to assign to List[i] (like List[0] on the first loop) will throw an IndexError because that index doesn't exist yet.
  • append() adds a new element to the end of the list, regardless of its current length. This is the correct way to build a list from scratch when you don't know the final size upfront.

2. EvenList[index] = List[i] vs EvenList.append(List[i])

  • Just like with the original list, EvenList starts empty. Using EvenList[index] requires that the index already exists in the list (i.e., the list has at least index + 1 elements). If you try this on an empty list, you'll get an IndexError.
  • append() dynamically adds elements to EvenList as you find even numbers, which is perfect because you don't know how many even numbers you'll end up with.

Now if you run the fixed code, it should collect even numbers correctly, print EvenList, and calculate the average without getting stuck!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:32:27