Как сделать аргументы неопределенными c в python? - PullRequest
0 голосов
/ 28 апреля 2020

У меня есть код в python для калькулятора стоимости магазина пиццы, который вычисляет стоимость после заказа, который может включать пиццу, напитки, крылышки и купоны. У него не обязательно должны быть все эти аргументы, у него будет разнообразие. Вот где я застрял. У меня есть код, но мне нужно использовать аргументы по умолчанию, чтобы сделать так, чтобы любое количество вставленных аргументов приводило к правильному выводу. (кое-что о позиционных аргументах)

Это код:

def pizza_cost(pizorders):
    total = 0
    for order in pizorders:
        total += 13
        if "pepperoni" in order:
            total = total + (x.count("pepperoni") * 1)
        if "mushroom" in order:
            total = total + (x.count("mushroom") * 0.5)
        if "olive" in order:
            total = total + (x.count("olive") * 0.5)
        if "anchovy" in order:
            total = total + (x.count("anchovy") * 2)
        if "ham" in order:
            total = total + (x.count("ham") * 1.5)
    return total

def drink_cost(driorders):
    total = 0
    for order in driorders:
        if order == "small":
            total = total + (x.count("small") * 2)
        if order == "medium":
            total = total + (x.count("medium") * 3)
        if order == "large":
            total = total + (x.count("large") * 3.5)
        if order == "tub":
            total = total + (x.count("tub") * 3.75)
    return total

def wing_cost(wingorders):
    total = 0
    for order in wingorders:
        if order == 10:
            total += 5
        if order == 20:
            total += 9
        if order == 40:
            total += 17.5
        if order == 100:
            total += 48
    return total


def cost_calculator(*pizzas, *drinks, *wings, *coupon):
    total = 0
    total += pizza_cost(pizzas)
    total += drink_cost(drinks)
    total += wing_cost(wings)
    tax = total * 0.0625
    discount = total * coupon
    total += tax
    total -= discount
    return total

И это ошибка:

   TypeError                                 Traceback (most recent call last)
~/opt/anaconda3/lib/python3.7/site-packages/bwsi_grader/__init__.py in compare_functions(student, soln, fn_args, fn_kwargs, function_name, comparison_function)
    110     try:
--> 111         student_out = student(*fn_args, **fn_kwargs)
    112     except Exception as e:

TypeError: cost_calculator() missing 3 required positional arguments: 'drinks', 'wings', and 'coupon'

During handling of the above exception, another exception occurred:

StudentError                              Traceback (most recent call last)
<ipython-input-13-322b790cbb8b> in <module>
      1 # Execute this cell to grade your work
      2 from bwsi_grader.python.pizza_shop import grader
----> 3 grader(cost_calculator)

~/opt/anaconda3/lib/python3.7/site-packages/bwsi_grader/python/pizza_shop.py in grader(student_func)
    191     for pizzas, items in zip(std_pizzas, std_orders):
    192         compare_functions(student=student_func, soln=soln,
--> 193                           fn_args=tuple(pizzas), fn_kwargs=items)
    194 
    195     for i in range(1000):

~/opt/anaconda3/lib/python3.7/site-packages/bwsi_grader/__init__.py in compare_functions(student, soln, fn_args, fn_kwargs, function_name, comparison_function)
    111         student_out = student(*fn_args, **fn_kwargs)
    112     except Exception as e:
--> 113         raise StudentError(f"\nCalling \n\t{pad_indent(sig, ln=4)}\nproduces the following error:"
    114                            f"\n\t{type(e).__name__}:{e}"
    115                            f"\nPlease run your function, as displayed above, in your Jupyter "

StudentError: 
Calling 
    student_function([])
produces the following error:
    TypeError:cost_calculator() missing 3 required positional arguments: 'drinks', 'wings', and 'coupon'
Please run your function, as displayed above, in your Jupyter notebook to get a detailed stacktrace of the error, and debug your function.

1 Ответ

0 голосов
/ 28 апреля 2020

Когда вы объявляете функцию, которая не использует аргументы по умолчанию, Python ожидает, что у вас будет обязательно иметь вход для каждого параметра. Аргумент по умолчанию позволит вам не вводить что-либо для аргумента.

def cost_calculator(pizza=[], drinks=[], wings=[], coupon=0.0):

     ''' your code here '''

Аргументы не по умолчанию называются позиционными аргументами, потому что они всегда должны вводиться и должны вводиться в правильном порядке.

Для аргументов по умолчанию вы должны убедиться, что вводите имя аргумента при вызове функции:

cost_calculator(drinks=['small', 'small', 'large'], coupon=0.2)

Я думаю, это должно работать в коде классификации. Они используют метод, называемый словарь для распаковки , который позволяет вам передать все параметры по умолчанию в качестве объекта словаря, который по соглашению называется kwargs :

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...