请求协助完善Python收集姓名与年龄的字典函数
Fixing Your Name & Age Collection Function
Let's walk through the issues in your code and fix them step by step to get a working solution:
Key Problems in Your Original Code
- Incorrect Input Handling:
input('Enter a name' and "Enter age for")doesn’t work as intended—andhere only returns the second string, and you can’t capture two separate values with oneinput()call. You need distinct prompts for name and age. - Broken Loop & Dictionary Logic: Your while loop references a
namevariable initialized outside the function, and the loop body has unrelated math code that doesn’t modify the dictionary. Also, dictionaries don’t use+to add entries—you assign values withdict[key] = value. - Scope Issue: The empty dictionary is defined outside the function, so it would retain data between function calls. It should be created inside the function to start fresh each time.
- Missing Age Handling: You commented out the age input, but we need to capture this value (and convert it to an integer since age is numeric).
Corrected Working Code
Here’s a version that meets your requirements, plus the average age summary you mentioned in your print statement:
def collect_names_ages(): people = {} # Empty dictionary initialized inside the function for clean scope while True: name = input("Enter a name (type 'END' to stop): ") if name == 'END': break # Exit the loop when user signals they're done # Handle invalid age inputs to avoid crashes try: age = int(input(f"Enter age for {name}: ")) except ValueError: print("Oops, please enter a valid number for age.") continue # Skip to next iteration if age is not a number people[name] = age # Add the name-age pair to the dictionary return people # Run the function and store the result person_dict = collect_names_ages() # Calculate and display the summary num_people = len(person_dict) if num_people > 0: average_age = sum(person_dict.values()) / num_people print(f"You have entered {num_people} names of people, whose average age is {average_age:.2f}.") else: print("No names were entered.")
Explanation of Changes
- Clean Function Scope: The empty dictionary
peoplelives inside the function, so it’s reset every time you callcollect_names_ages(). - Intuitive Loop Control:
while Truecreates an infinite loop that breaks when the user types 'END'—this is simpler than checking a variable initialized outside the loop. - Input Validation: The
try-exceptblock catches cases where the user enters non-numeric ages, preventing the program from crashing and prompting them to try again. - Proper Dictionary Updates: We add entries using
people[name] = age, the standard way to assign key-value pairs in Python dictionaries. - Summary Calculation: After collecting the data, we calculate the number of people (using the dictionary’s length) and average age (sum of values divided by count), then print a formatted summary.
内容的提问来源于stack exchange,提问作者JBreal1
相关产品推荐
相关产品推荐

