Python Docs

Python Functions — Full Cheat Sheet

A function is a reusable block of code that runs only when it is called. It helps prevent repetition and improves code structure.

What is a Function?

A function:

  • Helps avoid repeating code.
  • Can return data using return.
  • Makes programs cleaner and more modular.

Creating a Function

Use the def keyword followed by a function name and parentheses.

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

Python uses indentation to define the code block inside a function.

Calling a Function

Use the function name followed by parentheses to execute it.

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

my_function()

Calling Multiple Times

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

my_function()
my_function()
my_function()

Function Names

Function names follow the same rules as Python variable names:

  • Must start with a letter or an underscore (_)
  • Can contain letters, numbers, and underscores
  • Are case-sensitive

Valid Function Names

def calculate_sum():
  pass

def _private_function():
  pass

def myFunction2():
  pass

Why Use Functions?

Functions prevent code repetition and help you write clean, maintainable programs.

Without Functions (Repetitive Code)

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 (Reusable Code)

def fahrenheit_to_celsius(f):
  return (f - 32) * 5/9

print(fahrenheit_to_celsius(77))
print(fahrenheit_to_celsius(95))
print(fahrenheit_to_celsius(50))

Return Values

Use return to send a value back to the caller.

Function Returning a Value

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

message = get_greeting()
print(message)

Using Return Value Directly

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

print(get_greeting())

The pass Statement

Use pass when defining a function with no body yet. It acts as a placeholder.

def my_function():
  pass

This is useful when planning your function structure before adding logic.