LEARN COMPLETE PYTHON IN 24 HOURS

12. Functions – Reusing Code

A function is a block of code that performs a specific task. You define it once and call it many times — avoids repetition (DRY principle: Don't Repeat Yourself).

12.1 Defining & Calling Functions

Syntax to define a function:

Python

def function_name(parameters): # optional parameters # code to execute # optional return statement

Calling (using) the function:

Python

function_name(arguments)

Example – Simple function

Python

def greet(): print("Hello, Anshuman!") print("Welcome to Python 2026!") # Call the function greet() greet() # You can call it multiple times

Output:

text

Hello, Anshuman! Welcome to Python 2026! Hello, Anshuman! Welcome to Python 2026!

Example with parameter

Python

def greet(name): print(f"Hello, {name}! How are you?") greet("Anshuman") greet("Rahul")

Output:

text

Hello, Anshuman! How are you? Hello, Rahul! How are you?

Tip: Function name should be lowercase with underscores (snake_case) — e.g., calculate_area

12.2 Parameters vs Arguments

  • Parameter: Variable listed inside the parentheses in the function definition (placeholder)

  • Argument: Actual value passed when you call the function

Python

def add(a, b): # a, b are parameters print(a + b) add(5, 3) # 5, 3 are arguments add(10, 20) # positional arguments

Output:

text

8 30

12.3 Default Arguments

You can give parameters default values — they become optional.

Syntax:

Python

def function_name(param=default_value): ...

Example:

Python

def greet(name="Guest"): print(f"Hello, {name}! Welcome!") greet("Anshuman") # Hello, Anshuman! Welcome! greet() # Hello, Guest! Welcome!

Important Rule: Default parameters must come after non-default ones

Python

# Correct def info(name, age=25, city="Muzaffarpur"): print(name, age, city) # Wrong → SyntaxError # def info(age=25, name, city): ...

12.4 Keyword Arguments

Pass arguments using parameter names — order doesn't matter.

Example:

Python

def person_info(name, age, city): print(f"{name} is {age} years old from {city}") person_info(age=25, name="Anshuman", city="Muzaffarpur") # Order doesn't matter when using keywords

Mix positional + keyword (positional first)

Python

person_info("Rahul", city="Patna", age=24)

Tip: Keyword arguments make code more readable when there are many parameters.

12.5 args and *kwargs

Used when you don't know how many arguments will be passed.

  • *args → collects extra positional arguments into a tuple

  • **kwargs → collects extra keyword arguments into a dictionary

*Example – args

Python

def sum_numbers(*args): total = 0 for num in args: total += num return total print(sum_numbers(1, 2, 3)) # 6 print(sum_numbers(10, 20, 30, 40)) # 100 print(sum_numbers()) # 0

**Example – kwargs

Python

def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Anshuman", age=25, city="Muzaffarpur", hobby="coding")

Output:

text

name: Anshuman age: 25 city: Muzaffarpur hobby: coding

Combined Example

Python

def advanced_func(a, b, args, *kwargs): print("a:", a) print("b:", b) print("args:", args) print("kwargs:", kwargs) advanced_func(10, 20, 30, 40, name="Test", city="Bihar")

Output:

text

a: 10 b: 20 args: (30, 40) kwargs: {'name': 'Test', 'city': 'Bihar'}

Tip: Common in real libraries (e.g., print(), matplotlib.plot())

12.6 Return Statement

return sends a value back to the caller. Function stops after return.

Examples:

Python

def square(num): return num * num result = square(5) print(result) # 25 print(square(10)) # 100

Multiple returns (one at a time)

Python

def check_even_odd(num): if num % 2 == 0: return "Even" else: return "Odd" print(check_even_odd(10)) # Even

Return multiple values (packs into tuple)

Python

def get_person(): return "Anshuman", 25, "Muzaffarpur" name, age, city = get_person() # unpacking print(name, age, city)

Tip: If no return, function returns None by default.

12.7 Scope – Local vs Global Variables

Local scope → Variables defined inside function (only accessible inside) Global scope → Variables defined outside (accessible everywhere, but careful)

Example:

Python

x = 100 # global def my_func(): y = 200 # local print("Inside function: x =", x) # can read global print("y =", y) my_func() print("Outside: x =", x) # print(y) # Error! y is local

Modify global inside function

Python

count = 0 def increment(): global count count += 1 print("Count:", count) increment() # Count: 1 increment() # Count: 2 print(count) # 2

Tip: Avoid modifying globals too much — pass as parameters instead for cleaner code.

12.8 Lambda Functions (Anonymous Functions)

Short, nameless functions — used for one-liners.

Syntax:

Python

lambda arguments: expression

Examples:

Python

# Normal function def square(x): return x x # Lambda equivalent square_lambda = lambda x: x x print(square_lambda(5)) # 25

Common uses – with map(), filter(), sort()

Python

numbers = [1, 2, 3, 4, 5] # Double each doubled = list(map(lambda x: x * 2, numbers)) print(doubled) # [2, 4, 6, 8, 10] # Filter even evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4] # Sort by length words = ["apple", "banana", "kiwi"] sorted_words = sorted(words, key=lambda w: len(w)) print(sorted_words) # ['kiwi', 'apple', 'banana']

Mini Project – Calculator using Functions

Python

def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x y def divide(x, y): if y == 0: return "Cannot divide by zero!" return x / y operations = { "+": add, "-": subtract, "": multiply, "/": divide } print("Simple Calculator") num1 = float(input("First number: ")) op = input("Operator (+ - * /): ") num2 = float(input("Second number: ")) if op in operations: result = operations[op](num1, num2) print(f"{num1} {op} {num2} = {result}") else: print("Invalid operator!")

This completes the full Functions section — now you can write reusable, powerful code!