← Back to Chapters

Python Functions

? Python Functions

⚡ Quick Overview

A function in Python is a block of reusable code that performs a specific task. Functions help you:

  • Organize code into logical blocks.
  • Avoid repetition by reusing the same logic.
  • Make programs easier to read, test, and maintain.

? Key Concepts

  • Function: Named block of code that runs when called.
  • def keyword: Used to define a function.
  • Parameters: Variables listed in the function definition.
  • Arguments: Actual values passed to the function when calling it.
  • return: Sends a value back from the function to the caller.
  • Function call: Line of code that executes the function.

? Syntax and Theory

Basic syntax of a user-defined function in Python:

? View Generic Function Syntax
def function_name(parameters):
    # function body
    # write your logic here
    return value  # optional

# calling the function
function_name(arguments)

Indentation is very important in Python. The code inside the function must be indented at the same level, usually 4 spaces.

? Code Examples

? Simple Function (No Parameters)

This function prints a greeting message. It has no parameters and no return value.

? View Code Example
def greet():
    print("Hello, World!")

greet()  # Call the function

? Function with Parameters

This version of greet() takes a name parameter so it can greet different people.

? View Code Example
# define a function that greets a person by name
def greet(name):
    print(f"Hello, {name}!")  # print a personalized greeting

# call the function with different names
greet("Alice")
greet("Bob")

➕ Function with Return Value

This function adds two numbers and returns the result instead of printing it directly.

? View Code Example
def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # 8

? Live Output and Explanation

?️ What These Programs Print

  • For the simple greet() function:
    Hello, World!
  • For greet("Alice") and greet("Bob"):
    Hello, Alice!
    Hello, Bob!
  • For the add(5, 3) call:
    8

When you call a function, Python jumps to the function body, executes it, and then comes back to the line after the call. If the function uses return, the returned value can be stored in a variable or used in an expression.

? Helpful Tips

  • Use functions to break your code into logical sections.
  • Use parameters to make functions flexible and reusable.
  • Use return to get results from a function instead of printing inside it.
  • Give functions meaningful names that describe what they do.
  • Keep functions small and focused on a single task.

? Practice Tasks

  • Write a function that prints your name.
  • Create a function that takes two numbers and returns their sum.
  • Write a function that checks if a number is even or odd.
  • Write a function that returns the maximum of three numbers.