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

Python读取10个不重复数字代码问题:列表长度无法达10的原因排查

Why Your Code Can't Collect 10 Unique Numbers

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 for loop for a while loop that checks the length of lst on every cycle. It only stops running when len(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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 21:07:28