Skip to content

Python Functions

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.

Why use Functions?

  1. Reusability: Define code once, and use it many times.
  2. Organization: Break down large programs into smaller, manageable pieces.
  3. Abstraction: You don't need to know how the function works, just what it does (like a remote control).

Components of a Function

  • Definition: Creating the function.
  • Arguments/Parameters: The information you send into the function.
  • Body: The code that performs the task.
  • Return Value: The result the function sends back.

Logic First

Think of a function like a recipe. The recipe is the definition; the ingredients are the parameters; the cooking is the body; and the finished dish is the return value.

Creating a Function

In Python, a function is defined using the def keyword:

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

Calling a Function

To call a function, use the function name followed by parenthesis:

my_function()

Arguments (Parameters)

Information can be passed into functions as arguments.

def greet(name):
  print(f"Hello, {name}!")

greet("Vishnu")
greet("Student")

Return Values

To let a function return a value, use the return statement:

def multiply(x):
  return 5 * x

result = multiply(3)
print(result) # 15

The *args and **kwargs

  • *args: If you do not know how many arguments will be passed into your function.
  • **kwargs: If you do not know how many keyword arguments will be passed.

Global vs Local Variables

Variables created inside a function are local and cannot be used outside. Variables created outside are global.