
In Python, a function is defined using the def keyword, followed by a function name and parentheses:
def my_function():
print("Hello from a function")This creates a function named my_function that prints "Hello from a function" when called.
To call a function, write its name followed by parentheses:
def my_function():
print("Hello from a function")
my_function()You can call the same function multiple times:
def my_function():
print("Hello from a function")
my_function()
my_function()
my_function()Function names follow the same rules as variable names in Python:
calculate_sum()
_private_function()
myFunction2()Imagine you need to convert temperatures from Fahrenheit to Celsius several times in your program. Without functions, you would have to write the same calculation code repeatedly:
temp1 = 77
celsius1 = (temp1 - 32) * 5 / 9
print(celsius1)
temp2 = 95
celsius2 = (temp2 - 32) * 5 / 9
print(celsius2)
temp3 = 50
celsius3 = (temp3 - 32) * 5 / 9
print(celsius3)With functions, you write the code once and reuse it:
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9
print(fahrenheit_to_celsius(77))
print(fahrenheit_to_celsius(95))
print(fahrenheit_to_celsius(50))Functions can send data back to the code that called them using the return statement.
When a function reaches a return statement, it stops executing and sends the result back:
def get_greeting():
return "Hello from a function"
message = get_greeting()
print(message)You can use the returned value directly:
def get_greeting():
return "Hello from a function"
print(get_greeting())Function definitions cannot be empty. If you need to create a function placeholder without any code, use the pass statement:
def my_function():
passThe pass statement is often used when developing, allowing you to define the structure first and implement details later.
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:
A function with one argument:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")The terms parameter and argument can be used for the same thing: information that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the actual value that is sent to the function when it is called.
def my_function(name): # name is a parameter
print("Hello", name)
my_function("Emil") # "Emil" is an argumentBy default, a function must be called with the correct number of arguments.
If your function expects 2 arguments, you must call it with exactly 2 arguments.
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")If you try to call the function with the wrong number of arguments, you will get an error:
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")You can assign default value to parameters. If the function is called without an argument, it uses the default value:
def my_function(name = "friend"):
print("Hello", name)
my_function("Emil")
my_function("Tobias")
my_function()
my_function("Linus")Default value for country parameter:
def my_function(country = "Norway"):
print("I am from", country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")You can send arguments with the key = value syntax.
def my_function(animal, name):
print("I have a", animal)
print("My", animal + "'s name is", name)
my_function(animal = "dog", name = "Buddy")This way, with keyword arguments, the order of the arguments does not matter.
def my_function(animal, name):
print("I have a", animal)
print("My", animal + "'s name is", name)
my_function(name = "Buddy", animal = "dog")When you call a function with arguments without using keywords, they are called positional arguments.
Positional arguments must be in the correct order:
def my_function(animal, name):
print("I have a", animal)
print("My", animal + "'s name is", name)
my_function("dog", "Buddy")The order matters with positional arguments:
Switching the order changes the result:
def my_function(animal, name):
print("I have a", animal)
print("My", animal + "'s name is", name)
my_function("Buddy", "dog")You can mix positional and keyword arguments in a function call.
However, positional arguments must come before keyword arguments:
def my_function(animal, name, age):
print("I have a", age, "year old", animal, "named", name)
my_function("dog", name = "Buddy", age = 5)You can send any data type as an argument to a function (string, number, list, dictionary, etc.).
The data type will be preserved inside the function:
Sending a list as an argument:
def my_function(fruits):
for fruit in fruits:
print(fruit)
my_fruits = ["apple", "banana", "cherry"]
my_function(my_fruits)Sending a dictionary as an argument:
def my_function(person):
print("Name:", person["name"])
print("Age:", person["age"])
my_person = {"name": "Emil", "age": 25}
my_function(my_person)Functions can return values using the return statement.
def my_function(x, y):
return x + y
result = my_function(5, 3)
print(result)Functions can return any data type, including lists, tuples, dictionaries, and more.
A function that returns a list:
def my_function():
return ["apple", "banana", "cherry"]To specify that a function can have only keyword arguments, add *, before the arguments.
def my_function(*, name):
print("Hello", name)
my_function(name = "Emil")Without *, you are allowed to use positional arguments even if the function expects keyword arguments:
def my_function(name):
print("Hello", name)
my_function("Emil")With *, you will get an error if you try to use positional arguments:
def my_function(*, name):
print("Hello", name)
my_function("Emil")You can combine both argument types in the same function.
Arguments before / are positional-only, and arguments after * are keyword-only:
def my_function(a, b, /, *, c, d):
return a + b + c + d
result = my_function(5, 10, c = 15, d = 20)
print(result)Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:
A function with one argument:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")The terms parameter and argument can be used for the same thing: information that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the actual value that is sent to the function when it is called.
def my_function(name): # name is a parameter
print("Hello", name)
my_function("Emil") # "Emil" is an argumentBy default, a function must be called with the correct number of arguments.
If your function expects 2 arguments, you must call it with exactly 2 arguments.
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")If you try to call the function with the wrong number of arguments, you will get an error:
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")You can assign default value to parameters. If the function is called without an argument, it uses the default value:
def my_function(name = "friend"):
print("Hello", name)
my_function("Emil")
my_function("Tobias")
my_function()
my_function("Linus")Default value for country parameter:
def my_function(country = "Norway"):
print("I am from", country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")You can send arguments with the key = value syntax.
def my_function(animal, name):
print("I have a", animal)
print("My", animal + "'s name is", name)
my_function(animal = "dog", name = "Buddy")This way, with keyword arguments, the order of the arguments does not matter.
def my_function(animal, name):
print("I have a", animal)
print("My", animal + "'s name is", name)
my_function(name = "Buddy", animal = "dog")When you call a function with arguments without using keywords, they are called positional arguments.
Positional arguments must be in the correct order:
def my_function(animal, name):
print("I have a", animal)
print("My", animal + "'s name is", name)
my_function("dog", "Buddy")The order matters with positional arguments:
Switching the order changes the result:
def my_function(animal, name):
print("I have a", animal)
print("My", animal + "'s name is", name)
my_function("Buddy", "dog")You can mix positional and keyword arguments in a function call.
However, positional arguments must come before keyword arguments:
def my_function(animal, name, age):
print("I have a", age, "year old", animal, "named", name)
my_function("dog", name = "Buddy", age = 5)You can send any data type as an argument to a function (string, number, list, dictionary, etc.).
The data type will be preserved inside the function:
Sending a list as an argument:
def my_function(fruits):
for fruit in fruits:
print(fruit)
my_fruits = ["apple", "banana", "cherry"]
my_function(my_fruits)Sending a dictionary as an argument:
def my_function(person):
print("Name:", person["name"])
print("Age:", person["age"])
my_person = {"name": "Emil", "age": 25}
my_function(my_person)Functions can return values using the return statement.
def my_function(x, y):
return x + y
result = my_function(5, 3)
print(result)Functions can return any data type, including lists, tuples, dictionaries, and more.
A function that returns a list:
def my_function():
return ["apple", "banana", "cherry"]To specify that a function can have only keyword arguments, add *, before the arguments.
def my_function(*, name):
print("Hello", name)
my_function(name = "Emil")Without *, you are allowed to use positional arguments even if the function expects keyword arguments:
def my_function(name):
print("Hello", name)
my_function("Emil")With *, you will get an error if you try to use positional arguments:
def my_function(*, name):
print("Hello", name)
my_function("Emil")You can combine both argument types in the same function.
Arguments before / are positional-only, and arguments after * are keyword-only:
def my_function(a, b, /, *, c, d):
return a + b + c + d
result = my_function(5, 10, c = 15, d = 20)
print(result)By default, a function must be called with the correct number of arguments.
However, sometimes you may not know how many arguments that will be passed into your function.
*args and **kwargs allow functions to accept an unknown number of arguments.
If you do not know how many arguments will be passed into your function, add a * before the parameter name.
This way, the function will receive a tuple of arguments and can access the items accordingly:
Using *args to accept any number of arguments:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")The *args parameter allows a function to accept any number of positional arguments.
Inside the function, args becomes a tuple containing all the passed arguments:
Accessing individual arguments from *args:
def my_function(*args):
print("Type:", type(args))
print("First argument:", args[0])
print("Second argument:", args[1])
print("All arguments:", args)
my_function("Emil", "Tobias", "Linus")You can combine regular parameters with *args.
Regular parameters must come before *args:
def my_function(greeting, *names):
for name in names:
print(greeting, name)
my_function("Hello", "Emil", "Tobias", "Linus")In this example, "Hello" is assigned to greeting, and the rest are collected in names.
*args is useful when you want to create flexible functions:
A function that calculates the sum of any number of values:
def my_function(*numbers):
total = 0
for num in numbers:
total += num
return total
print(my_function(1, 2, 3))
print(my_function(10, 20, 30, 40))
print(my_function(5))Finding the maximum value:
def my_function(*numbers):
if len(numbers) == 0:
return None
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
print(my_function(3, 7, 2, 9, 1))If you do not know how many keyword arguments will be passed into your function, add two asterisks ** before the parameter name.
This way, the function will receive a dictionary of arguments and can access the items accordingly:
Using **kwargs to accept any number of keyword arguments:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")The **kwargs parameter allows a function to accept any number of keyword arguments.
Inside the function, kwargs becomes a dictionary containing all the keyword arguments:
Accessing values from **kwargs:
def my_function(**myvar):
print("Type:", type(myvar))
print("Name:", myvar["name"])
print("Age:", myvar["age"])
print("All data:", myvar)
my_function(name = "Tobias", age = 30, city = "Bergen")You can combine regular parameters with **kwargs.
Regular parameters must come before **kwargs:
def my_function(username, **details):
print("Username:", username)
print("Additional details:")
for key, value in details.items():
print(" ", key + ":", value)
my_function("emil123", age = 25, city = "Oslo", hobby = "coding")You can use both *args and **kwargs in the same function.
The order must be:
def my_function(title, *args, **kwargs):
print("Title:", title)
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
my_function("User Info", "Emil", "Tobias", age = 25, city = "Oslo")The * and ** operators can also be used when calling functions to unpack (expand) a list or dictionary into separate arguments.
If you have values stored in a list, you can use * to unpack them into individual arguments:
Using * to unpack a list into arguments:
def my_function(a, b, c):
return a + b + c
numbers = [1, 2, 3]
result = my_function(*numbers) # Same as: my_function(1, 2, 3)
print(result)If you have keyword arguments stored in a dictionary, you can use ** to unpack them:
Using ** to unpack a dictionary into keyword arguments:
def my_function(fname, lname):
print("Hello", fname, lname)
person = {"fname": "Emil", "lname": "Refsnes"}
my_function(**person) # Same as: my_function(fname="Emil", lname="Refsnes")Remember: Use * and ** in function definitions to collect arguments, and use them in function calls to unpack arguments.