新程序员坚持使用elif

时间:2015-10-20 18:46:25

标签: python conditional

def computepay(h,r):
    if h <= 40 :
        p = r * h
        print p
    elif hrs >= 40 :
        p = r * 40 + (r * 1.5 * (h - 40) )
        print p
    else :
        Print "Error, you were payed to much"""


hrs = float(raw_input("Enter Hours:"))
# int can only represent whole numbers

rate = int(raw_input("Enter Rate:"))
# float can only represent floating-point values, that is, values that have a potential decimal place.
#r = float(rate)
p = computepay(h, r)
print "Pay",p

我正在尝试学习python,但无法弄清楚为什么我在elif函数上遇到computepay(h, r)错误。

2 个答案:

答案 0 :(得分:1)

初始化函数p = computepay(h,r)时,您传递的是非现有值hr(这只是函数的签名),您需要传递{{1}和hrs类似:rate

您的p = computepay(hrs,rate)中出现了一个小错字错误,您键入了要使用的变量,而不是您定义为函数签名的变量(elif)。

在您的函数定义中,您可以使用h,当您将其作为参数传递时,h将替换为hrs

所以你的elif会是:

elif h >= 40

你的比较含糊不清:

if h <= 40 :

查看=

elif h >= 40 :

修改:实际上它会转到您的if但会忽略您的elif,因为它已经匹配。

您的else区块中也存在拼写错误,它应该是print而不是Print,并且您的字符串末尾还有三"个字符。

答案 1 :(得分:1)

这没有给我任何错误:

def computepay(h,r):
    if h <= 40 :
        p = r * h
        return p
    elif h > 40 :
        p = r * 40 + (r * 1.5 * (h - 40) )
        return p
    else :
        return "Error, you were payed to much"

        h = float(raw_input("Enter Hours:"))
        # int can only represent whole numbers

        r = int(raw_input("Enter Rate:"))
        # float can only represent floating-point values, that is, values that have a potential decimal place.
        #r = float(rate)

        p = computepay(h, r)
        print "Pay",p

您的设置不是p = computepay(hrs, rate)hr未定义,因此即使您解决了身份错误,在修复之前这也不会有效。你应该返回值p,这是print "Pay",p的输出为Pay None的原因