函数缺少位置参数的错误

时间:2014-02-18 01:36:58

标签: python function

我的程序中出现错误,说finddiscount()缺少一个必需的位置参数。我似乎无法弄清楚如何正确编码找到折扣功能可以有人请帮忙吗?我确定这是一个简单的错误,但我是python的新手,尤其是函数新手。谢谢!

def finddiscount(discount):
        if quantity >= 1 and quantity <= 9:
            discount = "0%"
        elif quantity >= 10 and quantity <= 19:
            discount = "20%"
        elif quantity >= 20 and quantity <= 49:
            discount = "30%"
        elif quantity >= 50 and quantity <= 99:
            discount = "40%"
        elif quantity >= 100:
            discount = "50%"
        print (discount)    
    def main():
        quantity = int(input("How many packages where purchased?"))
        price = float(input("How much is each item?"))
        finddiscount()
        return
    def finddiscount(quantity):
        if quantity >= 1 and quantity <= 9:
            discount = "0%"
        elif quantity >= 10 and quantity <= 19:
            discount = "20%"
        elif quantity >= 20 and quantity <= 49:
            discount = "30%"
        elif quantity >= 50 and quantity <= 99:
            discount = "40%"
        elif quantity >= 100:
            discount = "50%"
        print (discount)    
    main()

3 个答案:

答案 0 :(得分:3)

您正在调用此功能

finddiscount()

但它定义如下

def finddiscount(quantity):

因此,您应该传递quantity参数的值。

finddiscount(quantity)

答案 1 :(得分:1)

您将函数定义为采用一个参数:

def finddiscount(discount):

(后来重新定义它,但是现在让我们忽略它,因为第二个定义也需要一个参数)。

但是你没有参数就叫它:

finddiscount()

大概你想要这个:

finddiscount(quantity)

您的代码还存在许多其他问题。您不应该在finddiscount函数定义中定义所有这些内容。并且你绝对不应该在具有相同名称的全局函数中定义名为finddiscount的本地函数。

此外,您通常希望您的函数实际上return某些内容,而不仅仅是print一个值,然后什么都不做。 (例如,您可能希望return折扣,因此稍后的某些代码可以将该折扣应用于price。)

但这会解决你问的问题。

答案 2 :(得分:0)

你可以避免if语句的级联(和意外的错误 - 如果数量= 0?或110?),如下所示:

import bisect
import sys

inp = raw_input if sys.hexversion < 0x3000000 else input

def type_getter(type_):
    def getfn(prompt):
        while True:
            try:
                return type_(inp(prompt))
            except ValueError:
                pass
    return getfn
get_int   = type_getter(int)
get_float = type_getter(float)

discount_points    = [     0, 10, 20, 50, 100]
discount_fractions = [.0, .0, .2, .3, .4,  .5]

def discount_fraction(qty):
    ndx = bisect.bisect_right(discount_points, qty)
    return discount_fractions[ndx]

def main():
    qty   = get_int("How many were purchased? ")
    price = get_float("How much is each?")

    frac = discount_fraction(qty)
    total = price * (1. - frac) * qty
    print("Final cost is ${:0.2f}.".format(total))

if __name__=="__main__":
    main()