If you’re new to Python, it’s recommended to read the Python Diaries - Chapter 1, Chapter 2, and Chapter 3 as we build on some concepts covered there.
What is a Function?
A function is a block of organized, reusable code that performs a single, related task. It enables modularity and code reuse. Think of a function as a black box—it takes input, processes it, and produces output.

def name_of_function(arguments):
# your code
return result # returning is optional
Example:
def sum_of_numbers(a, b):
c = a + b
return c
print(sum_of_numbers(2, 3))
Output: 5
Three main parts of a function:
- Input
- Logic/Code
- Output
Input
Data provided to the function for processing. It can be passed via:
- Parameters/arguments
- Global variables
- Memory location
Logic/Code
Statements that define what the function does with the input.
Logic can range from a single line to hundreds of lines depending on the task.
Output
The result of processing the input. Output can be provided via:
- Return statement
- Modification of a memory location
- Print statement
Variable Scope
- Local variables: Defined inside a function and inaccessible outside it.
- Global variables: Declared outside all functions, accessible inside if declared with
global.
Note: Global scope is module-wide. Built-in scope includes variables/literals defined by Python and usable anywhere in a program.
Returning Multiple Values
You can return multiple values from a function using a comma-separated list.
Example:
Given an array, find number K and return its index and the previous element (assume K is not at index 0 and elements are distinct).
array = [5, 6, 7, 12, 2, 4, 3, 9, 25, 29]
k = 29
def searching():
global array
global k
array.sort()
index = 0
while index < len(array):
if array[index] == k:
return index, array[index - 1]
index += 1
index, previous_value = searching()
print(index)
print(previous_value)
Output:
9
25
sort() vs sorted()
sort()modifies the original list in-place.sorted()returns a new sorted list.
Example:
array = [3, 4, 1, 2, 5]
new_arr = sorted(array)
print("array ->", array)
print("new_arr ->", new_arr)
array_2 = [2, 3, 5, 4, 1]
array_2.sort()
print("array_2 ->", array_2)
Output:
array -> [3, 4, 1, 2, 5]
new_arr -> [1, 2, 3, 4, 5]
array_2 -> [1, 2, 3, 4, 5]
Returning multiple values as a tuple: If you use a single variable on the left-hand side when returning multiple values, Python will pack them into a tuple.
That wraps up the basics of functions in Python. More advanced topics will follow in the upcoming articles. Stay tuned!









