Python代码报错IndentationError:if语句后需缩进块求助
问题原因
你遇到的IndentationError是因为Python对缩进有严格要求:if、else这类控制语句的代码块必须缩进(通常用4个空格),而你的代码里if hours > base_hours:之后的所有逻辑代码都没有缩进,导致Python无法识别哪些代码属于if的执行块。
修正后的代码
# Variables to represent the base hours and # the overtime multiplier. base_hours = 40 # Base hours per week ot_multiplier = 1.5 # Overtime multiplier # Get the hours worked and the hourly pay rate. hours = float(input('Enter the number of hours worked: ')) pay_rate = float(input('Enter the hourly pay rate: ')) # Calculate and display the gross pay. if hours > base_hours: # Calculate the gross pay with overtime. # First, get the number of overtime hours worked. overtime_hours = hours - base_hours # Calculate the amount of overtime pay. overtime_pay = overtime_hours * pay_rate * ot_multiplier # Calculate the gross pay. gross_pay = base_hours * pay_rate + overtime_pay else: # Calculate the gross pay without overtime. gross_pay = hours * pay_rate # Display the gross pay. print(f'The gross pay is ${gross_pay:,.2f}.')
说明
- 所有属于
if条件下执行的代码(从注释到gross_pay = ...)都缩进了4个空格,明确告诉Python这些代码是if成立时才会运行的块。 else下的代码同样缩进,确保逻辑归属正确。
内容的提问来源于stack exchange,提问作者Braham Cadet
相关产品推荐
相关产品推荐

