如何实现Python先收集全部输入再统一输出姓名首字母?
Fix: Collect All Inputs First, Then Output Initials Together
Got it, let's sort this out! The issue with your current code is that it prints each initial as soon as you enter a name—instead of storing all those initials first and then displaying them all at once.
What's Wrong with the Current Code?
Your loop prints each initial immediately after splitting the name, which is why you see output right after every input. We need to hold onto those initials until all names are entered.
Updated Code That Meets Your Needs
num_of_people = int(input("How many people will attend the meeting? ")) # Create an empty list to store all initials initials = [] for i in range(num_of_people): name = input(f"What is the full name of participant {i+1}? ") split_name = name.split(" ") # Calculate initials for this name and add to the list name_initials = [word[0] for word in split_name] # Join initials into a single string (e.g., "J D" for "John Doe") and add to the main list initials.append(' '.join(name_initials)) # Now print all initials together print("\nAll participant initials:") for idx, initial in enumerate(initials, 1): print(f"Participant {idx}: {initial}")
Breakdown of the Changes:
- Added an empty list
initials: This acts as a storage container for all the initial sets we'll generate. - List comprehension for initials: Instead of looping through each word to print, we use
[word[0] for word in split_name]to generate all initials for a single name at once. - Store initials instead of printing: We join the individual initials into a readable string (like "J S" for "Jane Smith") and add it to our
initialslist. - Print after all inputs: Once all names are entered, we loop through the
initialslist and print everything out in one go.
If you prefer a more compact output (like all initials in one line), you could replace the final loop with:
print("\nAll participant initials:", ", ".join(initials))
内容的提问来源于stack exchange,提问作者new_programmer
相关产品推荐
相关产品推荐

