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

将Python求平均值代码重构为函数时遇报错,求重构步骤指导

Hey there! Let's walk through refactoring your code into a proper function step by step. I'll break it down so you can see exactly what's going on, and fix those errors you're hitting.

Step 1: Start with the function definition

First, we'll use Python's def keyword to create a function. Let's give it a descriptive name so anyone reading the code knows what it does—something like calculate_three_number_average() makes perfect sense.

def calculate_three_number_average():
    # We'll add the rest of the code inside here
    pass

Step 2: Move the input logic into the function

Your original code gets three integer inputs from the user. We can paste that logic right inside the function, making sure to indent it properly (Python relies entirely on indentation to identify code blocks belonging to the function).

def calculate_three_number_average():
    n1 = int(input('Enter First Number: '))
    n2 = int(input('Enter Second Number: '))
    n3 = int(input('Enter Third Number: '))

Step 3: Calculate the average (cleaned up)

Your original calculation has a tiny redundant step: int(n1 + n2 + n3) is unnecessary because n1, n2, n3 are already integers from the input conversion. We can simplify it to just (n1 + n2 + n3) / 3 to get a float result (which is more accurate for averages, especially when the sum isn't divisible by 3).

Add this line inside the function:

average = (n1 + n2 + n3) / 3

Step 4: Fix the output logic

Your original print statement uses a comma which splits the output into two lines (and creates an unnecessary tuple in the background). Instead, we can use an f-string to combine the text and the average into a single clean print statement.

Add this inside the function:

# Option 1: Basic concatenation
print('\nThe Average Is:', average)
# Option 2: Cleaner f-string (preferred)
print(f'\nThe Average Is: {average}')

Step 5: Call the function to run it

Once the function is defined, you need to call it to execute the code inside. Just add this line at the bottom of your script:

calculate_three_number_average()

Full Working Code

Putting it all together, here's the complete refactored code:

def calculate_three_number_average():
    # Get user input for three numbers
    n1 = int(input('Enter First Number: '))
    n2 = int(input('Enter Second Number: '))
    n3 = int(input('Enter Third Number: '))
    
    # Calculate the average
    average = (n1 + n2 + n3) / 3
    
    # Print the result
    print(f'\nThe Average Is: {average}')

# Run the function
calculate_three_number_average()

Bonus: Make the function more flexible (optional)

If you want the function to accept numbers as parameters instead of handling input directly (which makes it reusable in other parts of your code), you can rewrite it like this:

def calculate_average(num1, num2, num3):
    return (num1 + num2 + num3) / 3

# Get input separately and call the function
n1 = int(input('Enter First Number: '))
n2 = int(input('Enter Second Number: '))
n3 = int(input('Enter Third Number: '))

average = calculate_average(n1, n2, n3)
print(f'\nThe Average Is: {average}')

Common Errors to Watch For

  • Indentation issues: Make sure all code inside the function is indented with 4 spaces (Python's standard). Forgetting to indent will throw a syntax error.
  • Forgetting to call the function: Defining the function doesn't run it—you need to add the function call at the end.
  • Redundant type conversion: As mentioned earlier, converting the sum of integers back to int is unnecessary and can lead to lost precision (e.g., if the sum isn't divisible by 3).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:18:37