From a previous post on Python Functions, we can look into how we can pass external arguments into Python functions. This will take our code and turn it into reusable chunks of code. Therefore this is good for a few reasons:
- It cuts down on lines of code, but if we need to repeat sections of code.
- When Python code is loaded into the interpreter, it is read line by line.
- We don’t want to waste resources on our computers by having Python repeatedly read the same line of code.
- It makes Python files simpler to read.
- Imagine trying to read a Python file that repeated 15 lines of code to do the same thing to different objects four times.
- Decreases size of Python file
- While this may not seem like a big deal, saving lines of code is a big deal when you get into the multi-file Python scripts/programs.
Passing Arguments into Python Functions
With functions, you can pass outside arguments into them. This is very simple, as all you have to do is give a variable name into the function for what you want to give. For example, if we are asking the user for input so we can add two numbers together:
def add_two(num1, num2):
return num1 + num2
in1 = int(input('Please enter a number: '))
in2 = int(input('Please enter another number: '))
res = add_two(in1,in2)
Pointing out a few things here,
- When you define the function’s arguments, those variable names have to match inside the function.
- They can be whatever names you want outside the function if you correctly pass them into it.
- You can only pass in the same number of arguments you are taking.
- It can not be less.
-
add_two(4)
Traceback (most recent call last): File "", line 1, in TypeError: add_two() missing 1 required positional argument: 'num2'
-
- It can not be more:
add_two(4,5,6) Traceback (most recent call last): File "", line 1, in TypeError: add_two() takes 2 positional arguments but 3 were given
- It can not be more:
When using functions for the first time, we can pass the function into help() to see how we should use it. When writing our functions, use docstrings to know what type of input the function seeks.
- If a user uses context-sensitive help in an IDE/Code Editor, it will show them what the program is looking for
- If not, you can use the function help() and wrap the function name in it to see its correct use.
- An example of docstring and associated printout:
def add_two(num1, num2):
'''
add_two(num1,num2)
The use of this function is to take two integers and add return the sum of them.
'''
return num1+num2
You can use *args and/or **kwargs
*args
What args allows you to input as many arguments as you want. When we add *args to our functions, we call it a variable once, and Inside the function, we can call it like below, just args, or with args. The best practice is just args.
def add_two(*args):
return sum(args)
If we were to run the above with more than two integers:
add_two(5,4,4)
13
**kwargs
**kwargs add keywords to the arguments. This allows you to take in an arbitrary number of key-value pairs and input them into a dictionary. An example:
def shopping_list(**kwargs):
if 'soda' in kwargs:
print(f"Dont get the {kwargs['soda']}, it is not good for you")
else:
print('There is no soda in the shopping cart')
Running the code with kwargs:
shopping_list(bread='Wonder', steak='Ribeye', soda='Mountain Dew', pizza='CPK', fruit='Apples')
Do not get the Mountain Dew, it is not good for you
Args and kwargs can be combined.
- How you have them defined is how you have to enter the variables.
- You can not go back after putting in the other.
- This means that if you start with args and start putting in kwargs, you can’t switch and go back to args.
A working example:
def myfunc(*args, **kwargs):
print(f'I would like {args[0]} helpings of {kwargs["food"]}')
When we run the above, it will look at position 0 of the argument and if a keyword argument exists with food as a key.
myfunc(6, 2, 1, 4, 5, 10, 12, soda='pepsi', food='sushi!', cars='X3') I would like 6 helpings of sushi!
A non-working example with args, kwargs, then args again:
myfunc(6, 2, 1, 4, 5, 10, 12, soda='pepsi', food='sushi!', cars='X3', 5, 3) File "", line 1 SyntaxError: positional argument follows keyword argument