-1

I'm doing beginner Kata on codewars and I'm confused about the way we used a function.

It has 3 arguments; a, b and margin. Turns out we have to initialise margin to 0 otherwise Python can't find it. But why do we not have to initialise a or b?

The function was close_margin(a, b, margin = 0): Why not close_margin(a = 0, b = 0, margin = 0): ?

The full code is as follows:

def close_compare(a, b, margin):

    if margin == '':

        margin = 0

    if a < b:

        return -1

    if a > b:

        return 1

    difference = a - b

    if margin > difference or margin == difference:

        return 0

And the resulting error code is:

Traceback (most recent call last):
File "main.py", line 4, in <module>
test.assert_equals(close_compare(4, 5), -1)
TypeError: close_compare() missing 1 required positional argument: 'margin'
Hydra17
  • 103
  • 7
  • 2
    You don't have to initialize any arguments if you don't want to. Could have been as simple as `close_margin(a, b, margin)`. But I guess in this case the function wants to use a default of `0` for `margin`. It really depends on what your function is doing. – r.ook Sep 18 '19 at 14:55
  • 1
    please provide the actual code and error message – Felk Sep 18 '19 at 14:55
  • This question should clear the difference between normal and keyword arguments: https://stackoverflow.com/questions/1419046/normal-arguments-vs-keyword-arguments – Hoog Sep 18 '19 at 14:57
  • Possible duplicate of [Normal arguments vs. keyword arguments](https://stackoverflow.com/questions/1419046/normal-arguments-vs-keyword-arguments) – Hoog Sep 18 '19 at 14:58

1 Answers1

1

The main purpose of a parameter is to accept an argument when the function is called. However, you can "initialize" a parameter with a default value when you define the function. If no argument is provided at call time, the default value will be used as if you had provided it explicitly.

Given a definition like

def foo(a, b, margin=0):
    ...

the following calls are identical:

foo(3, 5)  # Use the default value of 0 for the third parameter
foo(3, 5, 0)  # Provide a value of 0 for the third parameter

However, an unrelated feature is the ability to provide keyword arguments, which let you specify a value by name rather than position. Non-keyword arguments appear first, and are assigned to parameters in the order in which the parameters appear in the definition. Keyword arguments can appear in any order. All of the following are equivalent:

# All positional arguments
foo(3, 5, 0)
# Two positional, one keyword
foo(3, 5, margin=0)
# One positional, two keyword
foo(3, b=5, margin=0)
foo(3, margin=0, b=5)
# No positional, all keyword
foo(a=3, b=5, margin=0)
foo(b=5, margin=0, a=3)
foo(a=3, margin=0, b=5)
foo(b=5, a=3, margin=0)
foo(margin=0, a=3, b=5)
foo(margin=0, b=5, a=3)
chepner
  • 497,756
  • 71
  • 530
  • 681