Python is one of my favorite programming languages. It's simple and versatile. There's a reason it's so popular. It's fun to use, and you can get a lot of work done without writing a ton of code.
"I'll just write a quick Python script for this" - me, a bunch of times
One of the things Python does well is abstracting complexity. One example of that is the Python function. A function is a reusable set of instructions to perform a task. Functions aren't unique to Python; in fact, they work mostly the same as in other languages.
If you want to know how to write and call a function in Python, here's a step-by-step guide.
The Anatomy of a Python Function
Before you can call a function, you have to write a function. Thankfully, that's easy. Let's look at the main components of a function.
def function_name(parameters):
# Your code goes here
return
The keyword 'def' refers to a function definition followed by your chosen function name and parentheses enclosing optional parameters. Parameters are anything you want to put into the function.
The action happens in the function body (Where it says your code goes here). This is where we put statements that make the function do work.
The return keyword allows you to send data out of the function. Note: You don't always need to return a value. It's optional.
So the main parts are
- definition (def keyword)
- function name
- parameters
- body (what the function does)
- return value
All of these, put together, form a function.
Calling a Python Function
Once we've defined a function, calling it is as straightforward as writing the function's name followed by parentheses. If our function requires parameters, we place these inside the parentheses. These are optional.
Let's build a simple function to display Hello World whenever we call it.
def hello_world():
print("Hello, World!")
Even though there are no parameters or a return value, this is a function in Python. The "output" of the function is printing Hello World.
We can call this function with this line of code:
hello_world()
And this will output "Hello, World!" to your console whenever we call it.
In fact, if we call it five times:
hello_world()
hello_world()
hello_world()
hello_world()
hello_world()
It will display the same thing five times.
Congratulations, you've just written your first function in Python.
The Power of Function Parameters in Python
Parameters are pieces of data we pass into the function. The work of the function depends on what we pass into it. Parameters enable us to make our Python functions dynamic and reusable. We can define a function that takes parameters, allowing us to pass different arguments each time we call the function.
def greet(name):
print("Hello, " + name + "!")
greet("Jeremy")
greet("Susie")
greet("Jim")
Here, the greet()
function takes one parameter, 'name'. When we call the function, we can pass any name we wish to greet.
Dealing with Multiple Parameters
Python functions can accept multiple parameters, allowing us to add dynamic inputs to our function calls.
def greet(name, city):
print("Hello, " + name + " from " + city + "!")
greet("Jeremy", "Gaston")
greet("Susie", "Forest Grove")
greet("Jim", "Cornelius")
Now greet()
takes two parameters, 'name' and 'city'.
And it's that easy. Congrats, you can now pass data into a function in Python.
Leveraging Default Parameters in Python Functions
Sometimes, you want to set a value for a parameter as a default. This allows the function to be called even if no data was passed. Rather than throwing an error, it will populate the value with anything you specify.
def greet(name="User"):
print("Hello, " + name + "!")
greet()
greet("Alice")
Here, 'greet()' function has a default parameter 'name' set to 'User'. If no argument is passed, the function greets 'User'. If we provide a name, it greets that name instead.
It's a good way to set defaults.
Python Return Statement
The 'return' statement exits a function and returns a value. With it, we can store the output of a function in a variable for future use.
def square(number):
return number * number
result = square(5)
print(result)
In this case, square()
function returns the square of the input number. The output can be stored in a variable and used later.
The return keyword is used to push values out of the function to use in your program.
Functions are awesome!
Python functions are a powerful tool in a programmer's arsenal. They encapsulate code blocks for specific tasks, enhancing the readability and maintainability of the code. Understanding how to call a function in Python, employ parameters, and leverage the 'return' statement is fundamental to proficient Python programming.
Remember, practice is key! The more you use this, the more second nature it will be for you.
The Versatility of Variable Arguments in Python
Python introduces an interesting feature in functions: variable-length arguments. Sometimes we don't know how many arguments will be passed to a function. Python's variable arguments (*args and **kwargs) solve this problem.
def add_numbers(*args):
return sum(args)
print(add_numbers(3, 5, 7, 9))
In the example, add_numbers()
uses *args
to accept any number of parameters. The function then sums up all the numbers and returns the total.
In-Depth with Python Keyword Arguments
Python functions also allow keyword arguments, which enable us to identify arguments by name. This can be extremely handy when a function has many parameters, and it improves the readability of our code.
def describe_pet(pet_name, animal_type='dog'):
print("I have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name + ".")
describe_pet(pet_name='Willie')
In this scenario, 'describe_pet()' is called with the 'pet_name' keyword argument. The function also includes a default argument, 'animal_type', set to 'dog'.
Grasping Anonymous Functions in Python: Lambda
Python's 'lambda' function is a small, anonymous function defined with the 'lambda' keyword, rather than 'def'. Lambda functions can accept any number of arguments but only have one expression.
multiply = lambda x, y: x * y
print(multiply(5, 4))
In the code above, a lambda function is defined to multiply two numbers, and it's called with two arguments: 5 and 4. The function returns the result of the multiplication.
Conclusion
Congratulations, you now know how to work with functions in Python. We have covered:
- The main parts of a function
- Calling a Python function
- Using function parameters
- Using multiple parameters
- Creating default parameters
- Returning data with the return statement
- Using variable parameters
- Leveraging lambda functions
Functions in Python provide a way of organizing and reusing code to create cleaner programming solutions.
As a next step, we recommend you delve deeper into advanced Python function topics such as recursive functions, decorators, and generator functions. I'll be adding more content like this to this blog very soon.
Follow me on Dev.To and come back for more cool Python tutorials.