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

Python缩进错误求助:实现员工周薪计算逻辑遇IndentationError

Fixing IndentationError & Implementing Weekly Pay Calculation in Python

Hey there! Let's tackle that indentation error first, then build the weekly pay calculator exactly as you need it.

Why the IndentationError Happens

That IndentationError: expected an indented block on your hours = input(prompt1) line means this code is sitting right after a statement that requires an indented code block (like a def function definition, if condition, or for/while loop) but you didn’t add proper indentation (usually 4 spaces, Python’s standard).

For example, if you tried defining a function without indenting the code inside it, that’s exactly the error you’d get:

# Wrong - no indent after def
def get_hours():
hours = input("Enter hours worked:")

Correct Weekly Pay Calculator Code

Here’s a complete, working implementation that follows your pay rules, with proper indentation and input handling:

def calculate_weekly_salary():
    # Get user input (convert to float to handle partial hours/wages)
    hourly_wage = float(input("请输入你的小时工资:"))
    total_hours = float(input("请输入本周工作总小时数:"))
    
    # Calculate pay based on your rules
    if total_hours <= 40:
        # Regular pay only for standard hours
        weekly_pay = total_hours * hourly_wage
    else:
        # Regular pay for first 40 hours + overtime at 1.5x rate
        regular_pay = 40 * hourly_wage
        overtime_hours = total_hours - 40
        overtime_pay = overtime_hours * hourly_wage * 1.5
        weekly_pay = regular_pay + overtime_pay
    
    # Print result formatted to 2 decimal places (for currency)
    print(f"你的本周周薪为:{weekly_pay:.2f} 元")

# Run the calculator function
calculate_weekly_salary()

Key Details to Note

  • All code inside the calculate_weekly_salary() function is indented 4 spaces—this fixes the indentation error you ran into.
  • We convert input values to float so we can handle partial hours (like 42.5 hours) and non-whole-number wages.
  • The if/else block clearly separates regular pay from overtime pay, following your rule:
    • Regular pay: Hours ≤40 → total hours × hourly wage
    • Overtime pay: Hours >40 → (40 × wage) + (extra hours × wage × 1.5)
  • The result is formatted to 2 decimal places for clean, currency-friendly output.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:36:19