Python 3 – Functions
In Python programming, functions are used to execute a block of code when it’s called. They make your code more organized, maintainable, and re-usable. You can pass arguments to functions, and they can return values as well. In this article, we’ll discuss everything you need to know about functions in Python 3.
Defining Functions
A function is defined using the keyword def
, followed by the function name, followed by parentheses. Inside the parentheses, you can optionally specify one or more parameters separated by commas. The code block that runs when the function is called is indented below the function definition.
# Defining a function that greets the user
def greet(name):
print(f"Hello, {name}!")
In the example above, we defined a function called greet
that takes one parameter called name
. The print()
function inside the function is indented, which indicates that it’s part of the function code block. When we call the function and pass it a name argument, it will print a greeting to the console.
Calling Functions
To call a function, you simply need to specify the function name followed by parentheses, with any arguments passed inside the parentheses. Here’s an example of calling the greet()
function we defined earlier:
# Calling the `greet()` function
greet("Bob")
This will result in outputting Hello, Bob!
to the console.
Returning Values
Functions can also return values using the return
keyword. Here’s an example:
# Defining a function that returns the sum of two numbers
def add(x, y):
return x + y
In the example above, we defined a function called add
that takes two parameters (x
and y
) and returns their sum using the return
keyword. To call this function and get the result, we can assign the function call to a variable:
# Calling the `add()` function and storing the result in a variable
result = add(3, 5)
print(result) # Output: 8
Default Parameters
You can set default values for function parameters, which means that the parameter will have a default value if no value is provided when the function is called. Here’s an example:
# Defining a function that takes two parameters, with a default value for the second parameter
def show_info(name, age=18):
print(f"{name} is {age} years old.")
# Calling the `show_info()` function with one argument
show_info("Alice") # Output: Alice is 18 years old.
# Calling the `show_info()` function with two arguments
show_info("Bob", 25) # Output: Bob is 25 years old.
In the example above, we defined a function called show_info
that takes two parameters (name
and age
). We set a default value of 18 for age
, which means that if no value is provided for age
when the function is called, it will default to 18. We called the function twice – once with one argument (just the name), which uses the default value for age
, and once with two arguments (name and age).
Keyword Arguments
When calling a function, you can also use keyword arguments, which are arguments that are passed with a name-value pair syntax. Here’s an example:
# Defining a function that takes two parameters
def book_info(title, author):
print(f"{title} by {author}")
# Calling the `book_info()` function with keyword arguments
book_info(author="J.K. Rowling", title="Harry Potter") # Output: Harry Potter by J.K. Rowling
In the example above, we defined a function called book_info
that takes two parameters (title
and author
). When we call the function, we passed the arguments in a different order than they were defined, but we specified their corresponding parameter names using the keyword argument syntax.
Arbitrary Arguments
Functions can also take an arbitrary number of arguments using the *args
syntax. This is useful when you don’t know how many arguments the function will need to handle. Here’s an example:
# Defining a function that takes an arbitrary number of arguments
def multiply(*numbers):
result = 1
for number in numbers:
result *= number
return result
# Calling the `multiply()` function with different number of arguments
print(multiply(2, 3)) # Output: 6
print(multiply(4, 5, 6)) # Output: 120
In the example above, we defined a function called multiply
that takes an arbitrary number of arguments (*numbers
). The *
syntax before the parameter name tells Python to pack any extra arguments into a tuple, which can be iterated over using a loop. The function then multiplies all the numbers together and returns the result.
Keyword-only Arguments
In Python 3, you can create keyword-only arguments by using the *
syntax before the parameter name. This means that the argument can only be passed as a keyword argument and not as a positional argument. Here’s an example:
# Defining a function with keyword-only arguments
def check_grade(*, grade):
print(f"Your grade is {grade}")
# Calling the `check_grade()` function with keyword argument
check_grade(grade=85) # Output: Your grade is 85
# This will result in a TypeError, because the argument is not passed as a keyword argument
check_grade(85)
In the example above, we defined a function called check_grade
with one keyword-only argument called grade
. We called the function with a keyword argument, but if we try to call the function with a positional argument, Python will raise a TypeError
.
Conclusion
In conclusion, functions are an important and powerful feature of Python programming. They allow you to create modular, reusable code that can be called with different arguments to perform different tasks. Understanding how to define and call functions, as well as use different types of function parameters, is a fundamental skill for any Python programmer.