Functions in Python

August 02, 2025   5 Min Read 33

What You’ll Learn:

  • What is a function and why it's used
  • Defining and calling functions
  • Function parameters and arguments
  • Return values
  • Default, keyword, and variable-length arguments
  • Scope (Local vs Global)
  • Docstrings
  • Lambda (anonymous) functions
  • Practice tasks

What is a Function?

A Function is a reusable block of code that performs a specific task.

Instead of writing the same code multiple times, you can define a function once and call it anywhere in your code.

Benefits of Functions

  • Modularity: Break down your code into smaller pieces
  • Reusability: Reuse the same code mutliple times
  • Clarity: Makes the program easier to understand and debug
  • Maintainability: Easier to update specific logic.

Defining and Calling a Function

Syntax:


def function_name(parameters):
	# function body
	return value

Example:


def greet(name):
	return f"Hellow, {name}!"

print(greet("Akash")

Output: Hello, Akash!

Parameters vs Arguments

  • Parameter: A variable in the function definition
  • Argument: The actual value passed to the function

def add(a, b):  # a and b are parameters
	return a + b

print(add(3, 5))  # 3 and 5 are arguments

Return Statement

The return statement sends the result back to the caller.


def square(x):
	return x * x

result = square(4)

Types of Function Arguments

1. Default Arguments


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

greet()  # Output: Hello, Guest
greet("Akash")  # Output: Hello, Akash

If no value is passed, it used the default.

2. Keyword Arguments

Pass arguments by name (order doesn't matter):


def info(name, age):
	print(f"Name: {name}, Age: {age}")

info(age=25, name="Akash")

Output: Name: Akash, Age: 25

3. Variable-Length Arguments

a. *args (Non-keyworded variable argumnt)


def total(*numbers):
	return sum(numbers)

print(total(1, 2, 3, 4))  # Output: 10

Treated as a tuple.

b. **kwargs (Keyworded variabled arguments)


def display_info(**info):
	for key, value in info.items():
		print(f"{key}: {value}")

display_info(name="Akash", age=25, country="India")

Treated as a dictionary.

Scope in Python

  • Local Scope: Inside the function
  • Global Scope: Outside any function

x = 10  # Global

def show():
	x = 5  # Local
	print(x)

show()  # Output: 5
print(x)  # Output: 10

Use the global keyword to modify global variables inside a function.

Docstrings: Function Documentation

Write a short descrption inside the function using triple quotes (""" """)


def greet(name):
	"""This function greets the person by name."""
	return f"Hello, {name})"

print(greet.__doc__)

Output: This function greets the person by name.

Lambda Functions

Anonymous function using lambda keyword. Great for short, simple tasks.


square = lambda x: x * x
print(square(5))  # Output: 25

lambda is used where defining a function with def is too verbose.

Real-World Examples

Example1: Simple Calcualator


def calculator(a, b, operator):
	if operator == '+':
		return a + b
	elif operator == '-':
		return a - b
	elif operator == '*':
		return a * b
	elif operator == '/':
		return a / b
	else:
		return "Invalid operator"

print(calculator(4, 2, '*'))  # Output: 8

Practice Task

🔸 Create a function named analyze_string that:

  1. Accept a string
  2. Returns:
    • Total characters
    • Total vowels
    • Total consonants
    • String in uppercase

Sample Output:


analyze_string("Akash")
# Total Characters: 5
# Vowels: 2
# Consonants: 3
# Uppercase: AKASH

Summary Table

FeatureSyntax Example
Define functiondef func():
Call functionfunc()
Return valuereturn value
Default argsdef func(x=10)
*argsdef func(*args)
**kwargsdef func(**kwargs)
Lambda functionlambda x: x + 1
Scopeglobal, local
Docstring"""Documentation"""

Leave a Reply