未定义名称,我已经定义了名称

问题描述 投票:0回答:1

PFB下面的代码我正在尝试计算税额。为什么我得到NameError: name 'tax' is not defined.我在下面定义了税收,但仍会抛出未定义的错误税收。

    hw = float(input("Please enter total hours worked"))
    hp = float(input("Please enter the hourly rate"))

    # Pay and OT Calculations

    rp = hp * hw

    if hw == 40 or hw <40 :
        ot = 0
        tp = rp + ot

    elif hw > 40 and hw <50 :
        ot = (hw-40)*(hp*1.5)
        tp = rp + ot

    elif hw > 50 and hw < 60 :
        ot = (hw-40)*(hp*2)
        tp = rp + ot

    elif hw > 60 or hw == 60 :
        ot = (hw-40)*(hp*2.5)
        tp = rp + ot

    else :
        print ("Thanks")

    # tax Calculations

    if tp == 200 :
       tax = float((tp/100)*15)

    elif tp > 200 and tp < 300 :
         tax = ((tp-200)/100*20) + ((200/100)*15)

    elif tp >300 and tp < 400 :
         tax = ((tp-300)/100*25) + (((tp-200)-(tp-300))/100*20) + ((200/100)*15)

    elif tp >400 and tp == 400 :
         tax = ((tp-400)/100*30) + (((tp-200)-(tp-300)-(tp-400))/100*25) + (((tp-200)-(tp-300)/100)*20) + ((200/100)*15)

    else :
        print ("Thanks")

    # Printing Results

    print ("Your Salary has been credited")
    print ("Regular Pay = ", rp)
    print ("Overtime =", ot)
    print ("Gross Salary before tax deductions = ", tp)
    print ("Income Tax applicable =", tax)
python
1个回答
0
投票

您正在整个函数中使用变量,但仅在if / else情况下定义它们。这就增加了很多错误的余地,如[

...
if tp == 200 :
       tax = float((tp/100)*15)

    elif tp > 200 and tp < 300 :
         tax = ((tp-200)/100*20) + ((200/100)*15)

    elif tp >300 and tp < 400 :
         tax = ((tp-300)/100*25) + (((tp-200)-(tp-300))/100*20) + ((200/100)*15)

    elif tp >400 and tp == 400 :
         tax = ((tp-400)/100*30) + (((tp-200)-(tp-300)-(tp-400))/100*25) + (((tp-200)-(tp-300)/100)*20) + ((200/100)*15)

    else :
        # NO tax defined here
        print ("Thanks")
...

您应该在函数顶部将函数范围变量定义为:

    hw = float(input("Please enter total hours worked"))
    hp = float(input("Please enter the hourly rate"))

    rp = 0
    ot = 0
    tp = 0
    tax = 0

    # Pay and OT Calculations
    ...
    # Printing Results

    print ("Your Salary has been credited")
    print ("Regular Pay = ", rp)
    print ("Overtime =", ot)
    print ("Gross Salary before tax deductions = ", tp)
    print ("Income Tax applicable =", tax)

通过设置这些默认值,您一定不会在代码中遗漏变量initialization,并且在不需要更改税率的极端情况下,无需添加额外的逻辑来处理税率变量(else您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.