Functions help you organize your code into reusable blocks. Instead of writing the same code multiple times, you can create a function once and call it whenever needed. In this practice set, you’ll learn how to create functions, pass arguments, return values, use default parameters, and solve beginner-friendly Python programs. Python functions practice questions with solutions help to understand the concept
1. Python Program to Create and Call a Function
Problem Statement
Write a Python function that prints “Welcome to CodeMantra!” and call it.
Python Solution
def welcome():
print("Welcome to CodeMantra!")
welcome()
Sample Output
Welcome to CodeMantra!
Explanation
A function is created using the def keyword and executed by calling its name.
Concepts Covered
- Function
- def keyword
- Function Call
2. Python Program to Add Two Numbers Using a Function
Problem Statement
Write a Python function that accepts two numbers and prints their sum.
Python Solution
def add_numbers(num1, num2):
print("Sum:", num1 + num2)
add_numbers(15, 25)
Sample Output
Sum: 40
Explanation
Function parameters receive values passed during the function call.
Concepts Covered
- Function Parameters
- Function Arguments
3. Python Program to Find the Square of a Number Using a Function
Problem Statement
Write a Python function that returns the square of a number.
Python Solution
def square(number):
return number * number
result = square(8)
print(result)
Sample Output
64
Explanation
The return statement sends a value back to the function call.
Concepts Covered
- return Statement
4. Python Program to Check Whether a Number is Even or Odd Using a Function
Problem Statement
Write a Python function that checks whether a number is even or odd.
Python Solution
def check_even_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
print(check_even_odd(27))
Sample Output
Odd
Explanation
Functions can return different values based on conditions.
Concepts Covered
- if…else
- return
5. Python Program to Find the Largest of Three Numbers Using a Function
Problem Statement
Write a Python function that returns the largest among three numbers.
Python Solution
def largest(a, b, c):
return max(a, b, c)
print(largest(25, 80, 45))
Sample Output
80
Explanation
The built-in max() function returns the largest value.
Concepts Covered
- max()
- Function Return Value
6. Python Program to Calculate the Factorial of a Number Using a Function
Problem Statement
Write a Python function to calculate the factorial of a number.
Python Solution
def factorial(number):
result = 1
for i in range(1, number + 1):
result *= i
return result
print(factorial(5))
Sample Output
120
Explanation
The function multiplies numbers from 1 to the given number.
Concepts Covered
- for Loop
- Functions
7. Python Program to Use Default Function Arguments
Problem Statement
Write a Python function that greets a user. If no name is provided, print “Guest”.
Python Solution
def greet(name="Guest"):
print("Welcome", name)
greet()
greet("Rahul")
Sample Output
Welcome Guest
Welcome Rahul
Explanation
Default arguments are used when no value is passed during the function call.
Concepts Covered
- Default Arguments
8. Python Program to Return Multiple Values from a Function
Problem Statement
Write a Python function that returns both the sum and product of two numbers.
Python Solution
def calculate(a, b):
return a + b, a * b
sum_value, product = calculate(5, 10)
print("Sum:", sum_value)
print("Product:", product)
Sample Output
Sum: 15
Product: 50
Explanation
Python functions can return multiple values as a tuple.
Concepts Covered
- Multiple Return Values
9. Python Program to Calculate the Average of Numbers Using a Function
Problem Statement
Write a Python function that accepts three numbers and returns their average.
Python Solution
def average(a, b, c):
return (a + b + c) / 3
print(average(20, 30, 40))
Sample Output
30.0
Explanation
The function calculates the average and returns the result.
Concepts Covered
- Function Parameters
- Arithmetic Operations
10. Python Program to Find Whether a Number is Positive or Negative Using a Function
Problem Statement
Write a Python function that returns whether a number is positive, negative, or zero.
Python Solution
def check_number(number):
if number > 0:
return "Positive"
elif number < 0:
return "Negative"
else:
return "Zero"
print(check_number(-15))
Sample Output
Negative
Explanation
The function uses conditional statements to determine the type of number.
Concepts Covered
- Functions
- if…elif…else
- return Statement
11. Python Program to Create a Function That Returns Multiple Values
Problem Statement
Write a Python function that accepts three subject marks and returns the total marks, average marks, and grade.
Python Solution
def calculate_result(math, science, english):
total = math + science + english
average = total / 3
if average >= 90:
grade = "A"
elif average >= 75:
grade = "B"
elif average >= 60:
grade = "C"
else:
grade = "D"
return total, average, grade
total, average, grade = calculate_result(85, 92, 88)
print("Total Marks:", total)
print("Average Marks:", round(average, 2))
print("Grade:", grade)
Sample Output
Total Marks: 265
Average Marks: 88.33
Grade: B
Explanation
The function returns multiple values in the form of a tuple. These values are unpacked into separate variables for further processing.
Concepts Covered
- Functions
- Multiple Return Values
- Tuple Unpacking
- Conditional Statements
12. Python Program to Create a Recursive Function to Calculate the Sum of Natural Numbers
Problem Statement
Write a Python program to calculate the sum of the first n natural numbers using recursion.
Python Solution
def natural_sum(n):
if n == 1:
return 1
return n + natural_sum(n - 1)
number = int(input("Enter a number: "))
print("Sum =", natural_sum(number))
Sample Output
Enter a number: 10
Sum = 55
Explanation
The function repeatedly calls itself until the base condition (n == 1) is reached.
Concepts Covered
- Recursive Functions
- Base Case
- Function Calls
13. Python Program to Create a Function Using *args
Problem Statement
Write a Python function that accepts any number of arguments and returns their average.
Python Solution
def average(*numbers):
total = sum(numbers)
return total / len(numbers)
result = average(10, 20, 30, 40, 50)
print("Average =", result)
Sample Output
Average = 30.0
Explanation
The *args parameter allows a function to accept any number of positional arguments.
Concepts Covered
- *args
- Variable-Length Arguments
- sum()
- Functions
14. Python Program to Create a Function Using **kwargs
Problem Statement
Write a Python function that accepts student details using keyword arguments and displays them.
Python Solution
def student_details(**details):
print("Student Information")
for key, value in details.items():
print(f"{key}: {value}")
student_details(
Name="Rahul",
Age=21,
Course="Python",
City="Delhi"
)
Sample Output
Student Information
Name: Rahul
Age: 21
Course: Python
City: Delhi
Explanation
The **kwargs parameter accepts any number of keyword arguments and stores them in a dictionary.
Concepts Covered
- **kwargs
- Dictionaries
- Functions
- items()
15. Python Program to Create a Function That Accepts Another Function as an Argument
Problem Statement
Write a Python program to pass one function as an argument to another function.
Python Solution
def square(number):
return number ** 2
def calculate(function, value):
return function(value)
answer = calculate(square, 8)
print("Result =", answer)
Sample Output
Result = 64
Explanation
Functions in Python are first-class objects, meaning they can be passed as arguments, returned from other functions, and assigned to variables. This concept is widely used in callbacks, decorators, and functional programming.
Concepts Covered
- Higher-Order Functions
- Function Arguments
- Function Objects
- Functional Programming
16. Python Program to Create a Closure Function
Problem Statement
Write a Python program to create a closure that remembers a multiplication factor and multiplies any given number by that factor.
Python Solution
def multiplier(factor):
def multiply(number):
return number * factor
return multiply
double = multiplier(2)
triple = multiplier(3)
print("Double of 15:", double(15))
print("Triple of 15:", triple(15))
Sample Output
Double of 15: 30
Triple of 15: 45
Explanation
The inner function (multiply) remembers the value of factor even after the outer function has finished execution. This behavior is known as a closure.
Concepts Covered
- Closures
- Nested Functions
- Returning Functions
- Function Scope
17. Python Program to Create a Simple Function Decorator
Problem Statement
Write a Python program to create a decorator that displays a message before and after executing a function.
Python Solution
def decorator(func):
def wrapper():
print("Function execution started.")
func()
print("Function execution completed.")
return wrapper
@decorator
def greet():
print("Welcome to Python Functions!")
greet()
Sample Output
Function execution started.
Welcome to Python Functions!
Function execution completed.
Explanation
A decorator modifies the behavior of another function without changing its original code. The @decorator syntax is a convenient way to apply decorators.
Concepts Covered
- Decorators
- Wrapper Functions
- Nested Functions
- Function Objects
18. Python Program to Use Lambda Function for Sorting
Problem Statement
Write a Python program to sort a list of tuples based on the second element using a lambda function.
Python Solution
students = [
("Rahul", 85),
("Priya", 95),
("Aman", 78),
("Neha", 91)
]
students.sort(key=lambda student: student[1])
print("Sorted List:")
for student in students:
print(student)
Sample Output
Sorted List:
('Aman', 78)
('Rahul', 85)
('Neha', 91)
('Priya', 95)
Explanation
The lambda function acts as an anonymous function and specifies that sorting should be based on the second element of each tuple.
Concepts Covered
- Lambda Functions
- sort()
- Lists
- Anonymous Functions
19. Python Program to Implement Memoization Using Functions
Problem Statement
Write a Python program to calculate Fibonacci numbers efficiently using memoization.
Python Solution
memo = {}
def fibonacci(n):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fibonacci(n - 1) + fibonacci(n - 2)
return memo[n]
number = int(input("Enter a number: "))
print("Fibonacci Number:", fibonacci(number))
Sample Output
Enter a number: 10
Fibonacci Number: 55
Explanation
Memoization stores previously computed Fibonacci values in a dictionary. This avoids repeated calculations and significantly improves performance.
Concepts Covered
- Memoization
- Recursive Functions
- Dictionaries
- Dynamic Programming
20. Python Program to Create a Function with Type Annotations
Problem Statement
Write a Python function that accepts two integers, returns their product, and uses type annotations.
Python Solution
def multiply(a: int, b: int) -> int:
return a * b
result = multiply(15, 8)
print("Product =", result)
Sample Output
Product = 120
Explanation
Type annotations improve code readability and help IDEs, type checkers, and developers understand the expected parameter and return types. They do not enforce types at runtime unless additional tools are used.
Concepts Covered
- Function Annotations
- Return Type
- Parameters
- Python Best Practices
21. Python Program to Create a Function Execution Timer Using a Decorator
Problem Statement
Write a Python program to create a decorator that calculates and displays the execution time of a function.
Python Solution
import time
def execution_timer(func):
def wrapper():
start = time.time()
func()
end = time.time()
print(f"\nExecution Time: {end - start:.6f} seconds")
return wrapper
@execution_timer
def display_numbers():
for i in range(1, 100001):
pass
print("Task Completed Successfully.")
display_numbers()
Sample Output
Task Completed Successfully.
Execution Time: 0.002145 seconds
Explanation
The decorator records the start and end time of the function execution using Python’s time module. It then calculates the difference and displays the total execution time.
Concepts Covered
- Decorators
- Wrapper Functions
- Time Module
- Performance Measurement
22. Python Program to Create a Login Authentication Function Using Decorators
Problem Statement
Write a Python program that allows only authenticated users to access a protected function using decorators.
Python Solution
def authenticate(func):
def wrapper(username):
if username == "admin":
return func(username)
print("Access Denied!")
return wrapper
@authenticate
def dashboard(user):
print(f"Welcome {user}")
print("You have successfully logged in.")
dashboard("admin")
Sample Output
Welcome admin
You have successfully logged in.
Explanation
The decorator checks the username before executing the protected function. If authentication fails, access is denied.
Concepts Covered
- Decorators
- Authentication
- Wrapper Functions
- Function Objects
23. Python Program to Create a Function Call Counter
Problem Statement
Write a Python program to count how many times a function has been called.
Python Solution
def call_counter(func):
def wrapper():
wrapper.count += 1
print(f"Function Called {wrapper.count} Times")
func()
wrapper.count = 0
return wrapper
@call_counter
def greet():
print("Welcome to Python!")
greet()
greet()
greet()
Sample Output
Function Called 1 Times
Welcome to Python!
Function Called 2 Times
Welcome to Python!
Function Called 3 Times
Welcome to Python!
Explanation
The decorator maintains a counter using a function attribute. Every time the function is called, the counter increases by one.
Concepts Covered
- Decorators
- Function Attributes
- Wrapper Functions
- State Management
24. Python Program to Cache Expensive Function Results
Problem Statement
Write a Python program to cache the result of an expensive calculation so repeated calls with the same input return instantly.
Python Solution
cache = {}
def square(number):
if number in cache:
print("Returning Cached Value")
return cache[number]
print("Calculating...")
result = number ** 2
cache[number] = result
return result
print(square(12))
print(square(12))
Sample Output
Calculating...
144
Returning Cached Value
144
Explanation
The function first checks whether the result already exists in the cache dictionary. If it does, the cached value is returned instead of performing the calculation again.
Concepts Covered
- Dictionaries
- Function Caching
- Memoization
- Optimization
25. Python Program to Build a Simple Banking System Using Functions
Problem Statement
Write a Python program that simulates a simple banking system using functions for deposit, withdrawal, and balance checking.
Python Solution
balance = 10000
def deposit(amount):
global balance
balance += amount
print("Amount Deposited Successfully.")
def withdraw(amount):
global balance
if amount <= balance:
balance -= amount
print("Withdrawal Successful.")
else:
print("Insufficient Balance.")
def check_balance():
print("Current Balance: ₹", balance)
check_balance()
deposit(3000)
withdraw(2500)
check_balance()
Sample Output
Current Balance: ₹ 10000
Amount Deposited Successfully.
Withdrawal Successful.
Current Balance: ₹ 10500
Explanation
This program demonstrates how multiple functions work together to solve a real-world problem. Separate functions are responsible for depositing money, withdrawing money, and checking the current balance.
Concepts Covered
- Functions
- Global Variables
- Conditional Statements
- Real-World Project
- Modular Programming
Frequently Asked Questions (FAQs)
1. What is a function in Python?
A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you can define it once and call it whenever needed. Functions improve code readability, maintainability, and reusability.
Example:
def greet():
print("Welcome to Python!")
greet()
Output:
Welcome to Python!
2. What are the advantages of using functions in Python?
Functions offer several benefits:
- Reduce code duplication
- Improve code readability
- Make debugging easier
- Simplify testing
- Support modular programming
- Improve code reusability
- Make large applications easier to manage
Functions are considered one of the core building blocks of professional Python development.
3. What is the difference between parameters and arguments?
- Parameters are variables defined in the function definition.
- Arguments are the actual values passed to the function when it is called.
Example:
def add(a, b): # a and b are parameters
return a + b
result = add(10, 20) # 10 and 20 are arguments
print(result)
4. What is the difference between return and print()?
return | print() |
|---|---|
| Sends a value back to the caller | Displays output on the screen |
| Can be stored in a variable | Cannot be reused directly |
| Ends the function execution | Does not end the function |
| Used for calculations and data processing | Used mainly for displaying information |
Example:
def square(number):
return number * number
result = square(5)
print(result)
5. What are *args and **kwargs in Python?
*argsallows a function to accept any number of positional arguments.**kwargsallows a function to accept any number of keyword arguments.
Example:
def display(*args, **kwargs):
print(args)
print(kwargs)
display(
10,
20,
Name="Rahul",
Course="Python"
)
These features make functions more flexible and reusable.
6. What is recursion in Python?
Recursion is a programming technique where a function calls itself to solve a problem. Every recursive function must have a base case to stop further recursive calls.
Example:
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Recursion is commonly used for tree traversal, graph algorithms, divide-and-conquer algorithms, and mathematical computations.
7. What is a lambda function?
A lambda function is an anonymous (unnamed) function used for short operations. It is generally used with functions like sorted(), map(), filter(), and reduce().
Example:
square = lambda x: x ** 2
print(square(8))
Lambda functions are useful when you need a simple function for a short period.
8. What is a decorator in Python?
A decorator is a special function that modifies the behavior of another function without changing its original code. Decorators are widely used for logging, authentication, caching, performance measurement, and access control.
Example:
def decorator(func):
def wrapper():
print("Before Function")
func()
print("After Function")
return wrapper
@decorator
def hello():
print("Hello Python!")
hello()
Decorators are an advanced Python feature frequently used in frameworks such as Django and Flask.
9. What is the difference between local and global variables?
A local variable is declared inside a function and can only be accessed within that function.
A global variable is declared outside all functions and can be accessed throughout the program. To modify a global variable inside a function, use the global keyword.
Example:
count = 100
def update():
global count
count += 50
update()
print(count)
Understanding variable scope is important for writing reliable Python programs.
10. Why are Python functions important for interviews and real-world projects?
Functions are one of the most important topics in Python because they are the foundation of modular programming. Almost every real-world Python application uses functions to organize code efficiently.
Function-related interview questions often cover:
- User-defined functions
- Recursive functions
- Lambda functions
*argsand**kwargs- Closures
- Decorators
- Higher-order functions
- Function annotations
- Memoization
- Callback functions
Mastering Python functions helps you build scalable applications in Web Development, Data Science, Machine Learning, Automation, Artificial Intelligence, Backend Development, APIs, and Software Engineering. It also improves your ability to write clean, reusable, and maintainable code, making it a key skill for coding interviews and professional Python development.
Chapter Summary
After completing this chapter, you have learned:
- Creating functions
- Calling functions
- Function parameters
- Function arguments
- Return statement
- Default arguments
- Multiple return values
- Using functions with loops
- Using functions with conditions
- Writing reusable Python code
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
