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

Python循环录入6个唯一姓名求助:重复输入时需提示并重录

Hey there! I totally get what you're trying to do here—collect 6 unique names where duplicate entries don't count towards the 6 slots and prompt the user to try again. Your original code just appends every input directly without checking for duplicates, which is why it wasn't working as expected.

Here's a working solution that combines a for loop (to keep track of the 6 required names) with an inner while loop (to handle duplicate checks and re-prompting):

name_list = []
question = "Please enter a name: "

# Outer loop runs exactly 6 times to get 6 unique names
for _ in range(6):
    while True:
        current_name = input(question)
        if current_name in name_list:
            print("Please enter a unique name")
        else:
            name_list.append(current_name)
            break  # Exit the inner loop once we have a valid unique name

# Print out the final list of names
for name in name_list:
    print("- " + name.title())

Let me break down how this works:

  • The outer for _ in range(6) loop ensures we'll end up with exactly 6 names—each iteration corresponds to one valid, unique entry. We use _ instead of a variable name because we don't need to reference the loop counter here.
  • The inner while True loop keeps asking for input until the user provides a name that's not already in name_list. If they enter a duplicate, it shows the prompt and loops again without advancing the outer loop (so no slot is wasted).
  • Once a unique name is entered, we add it to the list and break out of the inner loop, letting the outer loop move on to collect the next name.

This way, you get exactly 6 unique names, and duplicates don't eat into your 6 entry slots—perfect for what you're aiming for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 13:32:55