Python Crash Course for Beginners | Python Function Arguments – A Comprehensive Guide
Python is a high-level, general-purpose programming language, widely known for its readability and simplicity. One of the most powerful features in Python is functions, which allow us to divide our code into smaller, reusable parts. In this article, we will explore Python function arguments in depth, discussing the different types of arguments and how to use them effectively. We will provide numerous coding examples and explanations to help you understand these concepts thoroughly.
What are Python Function Arguments?
In Python, a function is a block of code that performs a specific task. Functions can receive data in the form of arguments and return the result. Arguments are the values passed to a function when it is called. They enable us to write more flexible and reusable code. Python offers several types of function arguments:
- Positional arguments
- Keyword arguments
- Default arguments
- Variable-length arguments (*args and **kwargs)
- Keyword-only arguments
- Positional-only arguments
Positional Arguments
Positional arguments are the most common type of function arguments. They are passed to a function in the order they are defined. The position of the argument in the function call determines which parameter it is assigned to.
Example:
def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
greet("Ada", "Lovelace")
Output:
Hello, Ada Lovelace!
In this example, “Ada” is assigned to first_name
, and “Lovelace” is assigned to last_name
based on their positions in the function call.
Keyword Arguments
Keyword arguments allow us to pass arguments to a function using their names. This can make the code more readable and eliminate potential confusion when dealing with multiple arguments.
Example:
def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
greet(first_name="Ada", last_name="Lovelace")
Output:
Hello, Ada Lovelace!
Here, the arguments are assigned to the parameters based on their names, not their positions.
Default Arguments
Default arguments allow us to specify default values for parameters in a function. If a value for the parameter is not provided during the function call, the default value will be used.
Example:
def greet(first_name, last_name, title=""):
if title:
print(f"Hello, {title} {first_name} {last_name}!")
else:
print(f"Hello, {first_name} {last_name}!")
greet("Ada", "Lovelace")
greet("Grace", "Hopper", title="Dr.")
Output:
Hello, Ada Lovelace!
Hello, Dr. Grace Hopper!
In this example, the title
parameter has a default value of an empty string. If no value is provided for title
, the function call will use the default value.
Variable-Length Arguments
Variable-length arguments allow a function to accept an arbitrary number of arguments. There are two types of variable-length arguments: *args and **kwargs.
a. *args
*args is used to pass a variable number of non-keyword (positional) arguments to a function. It allows the function to accept any number of positional arguments. These arguments will be passed as a tuple.
Example:
def sum_numbers(*args):
total = 0
for number in args:
total += number
return total
result = sum_numbers(1, 2, 3, 4, 5)
print(result)
Output:
15
In this example, the sum_numbers
function accepts any number of positional arguments, which are passed as a tuple named args
. The function then iterates through the tuple and sums the numbers.
b. **kwargs
**kwargs is used to pass a variable number of keyword arguments to a function. It allows the function to accept any number of keyword arguments. These arguments will be passed as a dictionary.
Example:
def print_employee_data(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_employee_data(name="Ada Lovelace", title="Programmer", birth_year=1815)
Output:
name: Ada Lovelace
title: Programmer
birth_year: 1815
In this example, the print_employee_data
function accepts any number of keyword arguments, which are passed as a dictionary named kwargs
. The function then iterates through the dictionary and prints the key-value pairs.
Keyword-Only Arguments
Keyword-only arguments are arguments that must be passed using their names (as keyword arguments). They are defined after a single asterisk (*) in the function definition.
Example:
def greet(*, first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
greet(first_name="Ada", last_name="Lovelace")
Output:
Hello, Ada Lovelace!
In this example, the greet
function requires the first_name
and last_name
arguments to be passed as keyword arguments. A function call with positional arguments would raise a TypeError.
Positional-Only Arguments
Positional-only arguments are arguments that must be passed using their positions (as positional arguments). They are defined before a single forward slash (/) in the function definition. Positional-only arguments are available in Python 3.8 and later versions.
Example:
def multiply(a, b, /):
return a * b
result = multiply(3, 4)
print(result)
Output:
12
In this example, the multiply
function requires the a
and b
arguments to be passed as positional arguments. A function call with keyword arguments would raise a TypeError.
Argument Unpacking
Argument unpacking allows us to pass elements of a sequence (e.g., list or tuple) or a dictionary as individual arguments to a function. We use a single asterisk (*) to unpack elements of a sequence and a double asterisk (**) to unpack key-value pairs of a dictionary.
Example:
def print_coordinates(x, y, z):
print(f"Coordinates: ({x}, {y}, {z})")
point = (3, 4, 5)
print_coordinates(*point)
info = {"x": 1, "y": 2, "z": 3}
print_coordinates(**info)
Output:
Coordinates: (3, 4, 5)
Coordinates: (1, 2, 3)
In this example, the print_coordinates
function accepts three positional arguments. The elements of the tuple point
and the key-value pairs of the dictionary info
are unpacked and passed as individual arguments to the function.
Summary
In this article, we covered different types of Python function arguments, including positional arguments, keyword arguments, default arguments, variable-length arguments (*args and **kwargs), keyword-only arguments, positional-only arguments, and argument unpacking. Understanding these types of function arguments and how to use them effectively will help you write more flexible, reusable, and readable code in Python.
By mastering the various types of function arguments, you will be able to create functions that are more adaptable to different use cases and better suited for collaboration with other developers. With numerous coding examples and explanations provided, you should now have a solid understanding of Python function arguments and their practical applications.
Latest end-to-end Learn by Coding Projects (Jupyter Notebooks) in Python and R:
All Notebooks in One Bundle: Data Science Recipes and Examples in Python & R.
End-to-End Python Machine Learning Recipes & Examples.
End-to-End R Machine Learning Recipes & Examples.
Applied Statistics with R for Beginners and Business Professionals
Data Science and Machine Learning Projects in Python: Tabular Data Analytics
Data Science and Machine Learning Projects in R: Tabular Data Analytics
Python Machine Learning & Data Science Recipes: Learn by Coding
R Machine Learning & Data Science Recipes: Learn by Coding
Comparing Different Machine Learning Algorithms in Python for Classification (FREE)
There are 2000+ End-to-End Python & R Notebooks are available to build Professional Portfolio as a Data Scientist and/or Machine Learning Specialist. All Notebooks are only $29.95. We would like to request you to have a look at the website for FREE the end-to-end notebooks, and then decide whether you would like to purchase or not.