Functions in Python
Subject: Data Structures and Algorithms · Language: Python · Level: beginner · 6 min read
Understand def, parameters, arguments, return values, default arguments, scope, and reusable DSA helper functions.
A function is a reusable block of code that performs a specific task. Functions help us avoid repeating the same logic again and again. They also make a program easier to read because each function can represent one clear idea.
Parameters are variables written in the function definition. Arguments are actual values passed when the function is called. This difference is important because it helps students understand how data moves into a function.
The `return` statement sends a value back to the place where the function was called. Returning is not the same as printing. Printing only displays a value, but returning allows the answer to be stored, compared, or used in another expression.
For example, a function `is_even(n)` should return `True` or `False`. Then the main program can decide what message to print. This makes the function useful in many places, not only in one fixed output format.
In DSA, functions are used to separate helper logic. You may write functions for checking prime numbers, finding maximum, reversing a list, calculating factorial, performing binary search, or visiting graph nodes.
A good function should do one main job. If one function reads input, solves many tasks, prints output, and modifies many variables, it becomes difficult to test. Small, meaningful functions make code cleaner and interview explanations easier.
A function is a reusable block of code that performs a specific task. Instead of writing all logic in one place, we can create separate functions for separate work.
Functions make a program easier to read, test, debug, and reuse. For example, if a program needs to calculate sum many times, writing one `add` function is better than repeating the same addition logic again and again.
In DSA programs, functions help separate input-output from the main logic. This makes solutions cleaner and easier to explain in interviews.
Function Syntax
In Python, a function is created using the `def` keyword.
```python
def add(a, b):
return a + b
```
Here, `def` starts the function definition. `add` is the function name. The values inside parentheses, `a` and `b`, are parameters. The indented block is the function body.
Calling a Function
A function runs only when it is called.
```python
result = add(10, 20)
print(result)
```
Output
```text
30
```
Here, `10` and `20` are arguments. They are passed to the parameters `a` and `b`.
Parameters and Arguments
In `def add(a, b)`, `a` and `b` are parameters. In `add(10, 20)`, `10` and `20` are arguments.
This difference is useful in interviews because it shows you understand how data moves into a function.
return Statement
The `return` statement sends a value back to the place where the function was called.
```python
def square(n):
return n * n
```
When we call `square(5)`, the function calculates `5 * 5` and returns `25`. The returned value can be printed or stored in a variable.
Function Without return
A function can also perform an action without returning a value. For example, it may only print a message.
```python
def print_message():
print("Welcome")
```
Output note
```text
No output is shown until print_message() is called.
```
If a Python function does not return anything explicitly, it returns `None` by default.
Default Arguments
Python allows default values for parameters. If the caller does not pass that argument, the default value is used.
```python
def greet(name="Student"):
print("Hello", name)
```
Sample Output after calling `greet()`
```text
Hello Student
```
Default arguments are useful for optional settings, but in beginner DSA solutions, simple required parameters are usually enough.
Keyword Arguments
Python allows arguments to be passed using parameter names.
```python
def display(name, marks):
print(name, marks)
display(marks=85, name="Rahul")
```
Output
```text
Rahul 85
```
Keyword arguments can make function calls clearer when there are many values.
Local Variables
A variable created inside a function is local to that function. It usually cannot be used directly outside the function.
```python
def add(a, b):
total = a + b
return total
```
Here, `total` belongs to the function. This helps keep different parts of the program separate and avoids accidental changes.
Why Functions Matter in DSA
Functions are very useful in DSA because they separate main logic from helper logic. For example, a program may have separate functions to check prime number, reverse a string, find maximum, calculate sum, or search a list.
This makes large solutions easier to manage. If a bug appears in one small function, it is easier to find and fix than searching through a very long program.
Example Program
```python
def add(a, b):
return a + b
def multiply(a, b):
return a * b
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Sum =", add(x, y))
print("Product =", multiply(x, y))
```
Sample Input
```text
8
4
```
Output
```text
Enter first number: Enter second number: Sum = 12
Product = 32
```
This program has two functions: `add` and `multiply`. The main part reads input, calls both functions, and prints the returned answers.
Function Naming Tips
A function name should clearly describe what the function does. Names like `is_prime`, `find_max`, `calculate_sum`, and `reverse_string` are better than unclear names.
Good function names make code easier to read and easier to explain during interviews.
A function is a named block of reusable logic. Instead of keeping every line inside one long program, we can divide the solution into smaller parts. This makes code easier to read, test, and explain.
A function can return an answer using `return`. Returning is different from printing. Printing only shows output on the screen, while returning sends a value back to the caller so it can be stored, compared, or used in another calculation.
For example, a function named `is_prime(n)` should return `True` or `False`. Then the main program can decide what to print. This style keeps checking logic separate from output logic.
Functions are very useful in DSA because many problems need helper logic. Examples include checking prime number, finding maximum, reversing a string, calculating factorial, merging arrays, and performing DFS.
A good function should do one clear job. If a function becomes too long or handles too many responsibilities, it becomes harder to debug. Small functions with meaningful names make programs easier for students and interviewers to follow.
Practice Question
Create functions to find the square of a number, cube of a number, and maximum of two numbers. Read values, call the functions, and print the returned answers.