In this Python article we want to learn about Python Function Arguments, but before that let’s talk about Python Function, so What is Python Function ? function is a block of code that can be reused for doing specific task. Functions can take different argumenta and they are values that are passed inside function when it is called. in this article we want to talk about different types of function arguments and how we can use them correctly.
Python Function Arguments
First of all let’s talk about Python positional argument, most common type of function argument in Python is positional argument. these are arguments that are passed inside a function in the order they are listed in the function definition.
this is an example of a function that takes two positional arguments.
1 2 3 4 |
def sum(x, y): return x + y print(sum(10,6)) |
Run the code and this will be the result
Let’s talk about Python Function Default Argument, sometimes we want to give an argument a default value if there is no value passed in function. we can do this by specifying default value for the argument in the function definition like this.
1 2 3 4 |
def hello(name, greeting="Hello"): return f"{greeting} {name}" print(hello("geekscoders")) |
This is the result
Let’s talk about Python Keyword arguments, sometimes we want to pass arguments to function in a different order than they are listed in the function definition. we can do this by using keyword arguments. Python Keyword arguments are passed to the function with format argument=value.
This is an example of a function that takes two keyword arguments.
1 2 3 4 |
def hello(name, greeting="Hello"): return f"{greeting}, {name}" print(hello(greeting = "Weclome", name = "geekscoders")) |
Run the complete code and this will be the result
Python Arbitrary Arguments
Sometimes we want to pass an arbitrary number of arguments to a function. we can do this by using an arbitrary argument. you can create Python arbitrary argument with an asterisk (*) before the argument name.
This is an example of a function that takes an arbitrary number of arguments.
1 2 3 4 |
def average(*args): return sum(args) / len(args) print(average(5,7,8,9)) |
This will be the result
Sometimes we want to pass an arbitrary number of keyword arguments to a function. we can do this by using an arbitrary keyword argument. Python arbitrary keyword argument is denoted with two asterisks (**) before the argument name.
This is an example of a function that takes an arbitrary number of keyword arguments.
1 2 3 4 5 6 |
def print_kwargs(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print(print_kwargs(name="Geekscoders.com", city="New York")) |
This will be the result
So in this article we have learned the different types of arguments in Python. we have seen how to use positional arguments, default arguments, keyword arguments, arbitrary arguments and arbitrary keyword arguments with Python.