Python image

Python Functions

Python Functions

  • A function is a block of code which only runs when it is called.
  • A function can return data as a result.
  • A function helps avoiding code repetition.

Creating a Function

In Python, a function is defined using the def keyword, followed by a function name and parentheses:

Example

def my_function():
  print("Hello from a function")

This creates a function named my_function that prints "Hello from a function" when called.

The code inside the function must be indented. Python uses indentation to define code blocks.

Calling a Function

To call a function, write its name followed by parentheses:

Example

def my_function():
  print("Hello from a function")

my_function()

You can call the same function multiple times:

Example

def my_function():
  print("Hello from a function")

my_function()
my_function()
my_function()

Function Names

Function names follow the same rules as variable names in Python:

  • A function name must start with a letter or underscore
  • A function name can only contain letters, numbers, and underscores
  • Function names are case-sensitive (myFunction and myfunction are different)

Example

calculate_sum()
_private_function()
myFunction2()
It's good practice to use descriptive names that explain what the function does.

Why Use Functions?

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:

Example

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:

Example

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))

Return Values

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:

Example

def get_greeting():
  return "Hello from a function"

message = get_greeting()
print(message)

You can use the returned value directly:

Example

def get_greeting():
  return "Hello from a function"

print(get_greeting())
If a function doesn't have a return statement, it returns None by default.

The pass Statement

Function definitions cannot be empty. If you need to create a function placeholder without any code, use the pass statement:

Example

def my_function():
  pass

The pass statement is often used when developing, allowing you to define the structure first and implement details later.

Python Function Arguments

Arguments

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:

Example

A function with one argument:

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Parameters vs Arguments

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.

Example

def my_function(name): # name is a parameter
  print("Hello", name)

my_function("Emil") # "Emil" is an argument

Number of Arguments

By 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.

Example

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:

Example

This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil")

Default Parameter Values

You can assign default value to parameters. If the function is called without an argument, it uses the default value:

Example

def my_function(name = "friend"):
  print("Hello", name)

my_function("Emil")
my_function("Tobias")
my_function()
my_function("Linus")

Example

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")

Keyword Arguments

You can send arguments with the key = value syntax.

Example

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.

Example

def my_function(animal, name):
  print("I have a", animal)
  print("My", animal + "'s name is", name)

my_function(name = "Buddy", animal = "dog")
The phrase Keyword Arguments is often shortened to kwargs in Python documentation.

Positional Arguments

When you call a function with arguments without using keywords, they are called positional arguments.

Positional arguments must be in the correct order:

Example

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:

Example

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")

Mixing Positional and Keyword Arguments

You can mix positional and keyword arguments in a function call.

However, positional arguments must come before keyword arguments:

Example

def my_function(animal, name, age):
  print("I have a", age, "year old", animal, "named", name)

my_function("dog", name = "Buddy", age = 5)

Passing Different Data Types

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:

Example

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)

Example

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)

Return Values

Functions can return values using the return statement.

Example

def my_function(x, y):
  return x + y

result = my_function(5, 3)
print(result)

Returning Different Data Types

Functions can return any data type, including lists, tuples, dictionaries, and more.

Example

A function that returns a list:

def my_function():
  return ["apple", "banana", "cherry"]

Keyword-Only Arguments

To specify that a function can have only keyword arguments, add *, before the arguments.

Example

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:

Example

def my_function(name):
  print("Hello", name)

my_function("Emil")

With *, you will get an error if you try to use positional arguments:

Example

def my_function(*, name):
  print("Hello", name)

my_function("Emil")

Combining Positional-Only and Keyword-Only

You can combine both argument types in the same function.

Arguments before / are positional-only, and arguments after * are keyword-only:

Example

def my_function(a, b, /, *, c, d):
  return a + b + c + d

result = my_function(5, 10, c = 15, d = 20)
print(result)

Python Function Arguments

Arguments

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:

Example

A function with one argument:

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Parameters vs Arguments

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.

Example

def my_function(name): # name is a parameter
  print("Hello", name)

my_function("Emil") # "Emil" is an argument

Number of Arguments

By 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.

Example

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:

Example

This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil")

Default Parameter Values

You can assign default value to parameters. If the function is called without an argument, it uses the default value:

Example

def my_function(name = "friend"):
  print("Hello", name)

my_function("Emil")
my_function("Tobias")
my_function()
my_function("Linus")

Example

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")

Keyword Arguments

You can send arguments with the key = value syntax.

Example

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.

Example

def my_function(animal, name):
  print("I have a", animal)
  print("My", animal + "'s name is", name)

my_function(name = "Buddy", animal = "dog")
The phrase Keyword Arguments is often shortened to kwargs in Python documentation.

Positional Arguments

When you call a function with arguments without using keywords, they are called positional arguments.

Positional arguments must be in the correct order:

Example

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:

Example

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")

Mixing Positional and Keyword Arguments

You can mix positional and keyword arguments in a function call.

However, positional arguments must come before keyword arguments:

Example

def my_function(animal, name, age):
  print("I have a", age, "year old", animal, "named", name)

my_function("dog", name = "Buddy", age = 5)

Passing Different Data Types

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:

Example

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)

Example

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)

Return Values

Functions can return values using the return statement.

Example

def my_function(x, y):
  return x + y

result = my_function(5, 3)
print(result)

Returning Different Data Types

Functions can return any data type, including lists, tuples, dictionaries, and more.

Example

A function that returns a list:

def my_function():
  return ["apple", "banana", "cherry"]

Keyword-Only Arguments

To specify that a function can have only keyword arguments, add *, before the arguments.

Example

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:

Example

def my_function(name):
  print("Hello", name)

my_function("Emil")

With *, you will get an error if you try to use positional arguments:

Example

def my_function(*, name):
  print("Hello", name)

my_function("Emil")

Combining Positional-Only and Keyword-Only

You can combine both argument types in the same function.

Arguments before / are positional-only, and arguments after * are keyword-only:

Example

def my_function(a, b, /, *, c, d):
  return a + b + c + d

result = my_function(5, 10, c = 15, d = 20)
print(result)

Python *args and **kwargs

*args and **kwargs

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.

Arbitrary Arguments - *args

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:

Example

Using *args to accept any number of arguments:

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")
Arbitrary Arguments are often shortened to *args in Python documentation.

What is *args?

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:

Example

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")

Using *args with Regular Arguments

You can combine regular parameters with *args.

Regular parameters must come before *args:

Example

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.

Practical Example with *args

*args is useful when you want to create flexible functions:

Example

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))

Example

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))

Arbitrary Keyword Arguments - **kwargs

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:

Example

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")
Arbitrary Keyword Arguments are often shortened to **kwargs in Python documentation.

What is **kwargs?

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:

Example

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")

Using **kwargs with Regular Arguments

You can combine regular parameters with **kwargs.

Regular parameters must come before **kwargs:

Example

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")

Combining *args and **kwargs

You can use both *args and **kwargs in the same function.

The order must be:

  1. regular parameters
  2. *args
  3. **kwargs

Example

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")

Unpacking Arguments

The * and ** operators can also be used when calling functions to unpack (expand) a list or dictionary into separate arguments.

Unpacking Lists with *

If you have values stored in a list, you can use * to unpack them into individual arguments:

Example

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)

Unpacking Dictionaries with **

If you have keyword arguments stored in a dictionary, you can use ** to unpack them:

Example

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.