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

时间:2020-01-16 02:14:48

标签: python

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)

1 个答案:

答案 0 :(得分: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个案例。