Python程序开发求助:实现自定义数量数字的求和及平均值计算功能
Got it, let's fix this up for you! Your current code has some logic snags (like duplicate input prompts and incorrect use of sum()), so here's a clean, working version that does exactly what you need—copy-paste it and it'll run right away:
Working Python Program for Sum & Average Calculation
# Ask user how many numbers they want to enter number_count = int(input("How many numbers would you like to input? ")) # Initialize total sum to 0 total_sum = 0 # Loop to collect each number and add to the total for i in range(number_count): current_num = int(input(f"Enter number {i + 1}: ")) total_sum += current_num # Calculate average (sum divided by number of inputs) average = total_sum / number_count # Print out the results clearly print(f"\nTotal sum of your numbers: {total_sum}") print(f"Average of your numbers: {average}")
Quick Breakdown of How This Works
- Get input count: First we ask for the number of values you want to enter, converting the input to an integer since we need a whole number.
- Track total sum: We start with a total of 0, then add each input number to this total as we go.
- Simpler loop: A
forloop is perfect here because we know exactly how many times we need to ask for input (no messy counter checks like in your original code). - Calculate average: Just divide the total sum by the number of inputs—easy!
- Clear output: We print both the sum and average so you can see both results at a glance.
What Was Off in Your Original Code?
- You had duplicate "next number" prompts when your counter hit the target, which would make you enter extra numbers by mistake.
- The
sum()function is meant for iterables (like lists), not for adding two variables directly withsum(number + num). - You repeated the same
counter == strikecondition twice, which didn't add any useful logic.
内容的提问来源于stack exchange,提问作者the_wilche
相关产品推荐
相关产品推荐

