Functions In Python
Python Functions: Reusable Code Blocks
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.
1. Creating and Calling a Function
In Python, a function is defined using the def keyword.
def my_function():
print("Hello from a function")
# Calling the function
my_function()
2. Arguments & Parameters
Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses.
def greet(fname):
print(f"Hello, {fname}!")
greet("Tanis")
greet("Alice")
[!NOTE] Parameters vs Arguments: A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called.
3. Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
def full_name(fname, lname):
print(fname + " " + lname)
full_name("Royal", "Coding")
4. Default Parameter Value
If we call the function without an argument, it uses the default value.
def country_msg(country = "India"):
print("I am from " + country)
country_msg("Norway")
country_msg() # Uses default "India"
5. Return Values
To let a function return a value, use the return statement.
def multiply(x):
return 5 * x
result = multiply(3)
print(result) # Output: 15
6. Special Arguments (*args & **kwargs)
| Type | Syntax | Use Case |
| :--- | :--- | :--- |
| Arbitrary Arguments | *args | When you don't know how many arguments will be passed. (Receives a tuple) |
| Keyword Arguments | key=val | When you want to pass arguments with a key-value syntax. |
| Arbitrary Keyword Arguments | **kwargs | When you don't know how many keyword arguments there will be. (Receives a dictionary) |
Example *args:
def my_kids(*kids):
print("The youngest child is " + kids[2])
my_kids("Emil", "Tobias", "Linus")
pass
Function definitions cannot be empty. Use pass to avoid errors if you haven't written the logic yet.
def future_function():
pass