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 Trueloop keeps asking for input until the user provides a name that's not already inname_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
breakout 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
相关产品推荐
相关产品推荐

