NameError: name 'p' is not defined in

前端 未结 3 554
猫巷女王i
猫巷女王i 2021-01-29 01:52

This code executes, however, an error message \" NameError: name \'p\' is not defined in lines 7 and 11 - I tried adding float( ) around everything - same error - any ideas ???

相关标签:
3条回答
  • 2021-01-29 02:09

    You try to return p in a function where p is not declared. I think you want to do this:

    def computepay(hrs,rate):
        if 0 < hrs <=40:
            p = (hrs * rate)
        elif hrs > 40:
            p = (40 * rate + (hrs-40)*rate*1.5)
        print p
        return p 
    

    PS. The line hrs = float(input("Enter Hours:")) has a wrong indentation. Remove all white spaces before it.

    0 讨论(0)
  • 2021-01-29 02:19

    Well, it is not defined in the function, is it?

    There's no statement telling that:

    p = ...
    

    Perhaps you mean to assign p to "(40 * rate + (hrs-40)*rate*1.5)" if hrs > 40, and not only print it?

    0 讨论(0)
  • 2021-01-29 02:22

    If you read your script from top to bottom:

    def computepay(hrs,rate):
    

    The interpreter uses this to define a local function with name computepay. It then ignores everything in the block:

    if 0 < hrs <=40:
        print (hrs * rate)
    elif hrs > 40:
        print (40 * rate + (hrs-40)*rate*1.5)
    return p
    

    Then it executes input, converts the result into a float object using float, and creates a name rate which points to the float object:

    rate = float(input("Enter Rate per Hour:"))
    

    Then it executes computepay which does its thing and tries to return p, however, the intepreter has not yet seen any definition of p in the local scope. Even if we said global p to tell the interpreter to look in the global scope, it has not yet created the NAME which points to any object. So you get a NameError:

    p = computepay(hrs,rate)
    
    0 讨论(0)
提交回复
热议问题