Python读取10个不重复数字代码问题:列表长度无法达10的原因排查
Let's break down why your code isn't working as expected, and how to fix it quickly:
The core issue lies in how your loop is structured. Your current code uses a for loop that runs exactly 10 times—no matter what happens during each iteration. When you input a duplicate number, you use continue to skip adding it to the list, but this doesn’t "redo" that iteration. So if you enter even one duplicate, you waste a loop cycle without adding a unique value, leaving your final list shorter than 10 elements.
The Fix: Use a while Loop Instead
Instead of limiting yourself to 10 fixed tries, you want to keep asking for numbers until your list has exactly 10 unique values. Here’s the adjusted code:
lst = [] while len(lst) < 10: new_num = input("Enter any number: ") if new_num not in lst: lst.append(new_num) print(new_num) else: print("This number is already in the list! Please enter a new one.") print(lst)
What Changed & Why It Works
- We swapped the
forloop for awhileloop that checks the length oflston every cycle. It only stops running whenlen(lst)hits 10. - We added a user-friendly message to clarify when a duplicate is entered (you can remove this if you don’t need it, but it helps guide the user).
- Now, every time a duplicate is input, the loop simply repeats—no iterations are wasted—until a unique number is provided.
Why Your Original Code Failed
Suppose in your original code, you enter 2 duplicate numbers during the 10 iterations. That means only 8 unique numbers get added to the list, but the loop still ends after 10 tries. The continue statement just skips the rest of the code in that iteration, but the loop doesn’t get an extra chance to ask for a valid number.
内容的提问来源于stack exchange,提问作者user13714707

