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 == 0is true (for even numbers), the loop will keep running forever becauseList[i]never changes inside the loop. The condition stays true, so your program gets stuck here and never reaches theprintstatements 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 toList[i](likeList[0]on the first loop) will throw anIndexErrorbecause 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,
EvenListstarts empty. UsingEvenList[index]requires that the index already exists in the list (i.e., the list has at leastindex + 1elements). If you try this on an empty list, you'll get anIndexError. append()dynamically adds elements toEvenListas 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

