A Python function is a block of code that carries out a specific task. Functions make your code reusable, so you can run the same logic whenever you need it without writing it multiple times.
This article provides 18 Python functions practice questions that focus entirely defining functions, calling them, using arguments, working with inner functions, and exploring built-in functions
Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.
- All solutions have been fully tested on Python 3.
- Interactive Learning: Use our Online Code Editor to solve these exercises in real time.
If you have other solutions, please share them in the comments to help fellow developers.
Also Read:
- Python Functions Quiz: MCQs to help you get familiar with Python functions.
- Python functions and Python function arguments to solve questions
- Python Functions and Modules Interview Questions
+ Table of Contents (18 Exercises)
Table of contents
- Exercise 1. Create a Function with Parameters
- Exercise 2. Variable Length of Arguments ( *args )
- Exercise 3. Return Multiple Values from a Function
- Exercise 4. Function with Default Argument
- Exercise 5. Create an Inner Function
- Exercise 6. Create a Recursive Function
- Exercise 7. Assign a Different Name to Function and Call It
- Exercise 8. Generate a List of Even Numbers (Range Function)
- Exercise 9. Find the Largest Item in a List
- Exercise 10. Call Function using Positional and Keyword Arguments
- Exercise 11. Create a Function with Keyword Arguments
- Exercise 12. Modifying Global Variables
- Exercise 13. Recursive Factorial (Non-Negative Integers)
- Exercise 14. Create a Lambda Function to Square a Number
- Exercise 15. Filter a List Using Lambda and filter()
- Exercise 16. Transform a List Using Lambda and map()
- Exercise 17. Sort Complex Data with sorted() and Lambda
- Exercise 18. Create a Higher-Order Function
Exercise 1. Create a Function with Parameters
Practice Problem: Write a function called demo() that accepts two parameters: a name and an age. The function should print these values directly to the console.
Exercise Purpose: This is the foundation of modular programming. It teaches how to pass data from the main program into a function’s local scope, allowing the same logic to be reused with different datasets.
Given Input:
name = "Kelly"
age = 25Code language: Python (python)
Expected Output: Kelly 25
Hint
- Define the function using the
defkeyword followed by the parameters in parentheses. - Inside the function, use the
print()statement to display the variables.
Solution
Explanation to Solution:
def demo(name, age):: Thedefkeyword tells Python we are defining a function.nameandageare placeholders (parameters) that will receive values when the function is called.- Function Call: When we run
demo("Kelly", 25), the string “Kelly” is assigned tonameand 25 is assigned toage. - Print: The values are outputted as a single line, separated by a space by default.
Exercise 2. Variable Length of Arguments (*args)
Practice Problem: Create a function func1() such that it can accept a variable number of arguments and print all of them. Whether you pass two numbers or five, the function should handle them all without error.
Exercise Purpose: In real-world programming (like logging or mathematical operations), you often don’t know how many inputs a user will provide. Using *args allows your function to be flexible and “future-proof.”
Read: variable length of arguments in functions
Given Input:
Call 1: func1(20, 40, 60)
Call 2: func1(80, 100)Code language: Python (python)
Expected Output:
Printing values:
20
40
60
Printing values:
80
100
Hint
- Use the asterisk
*before the parameter name in the function definition. This packs all passed arguments into a tuple. - Use a
forloop to iterate through that tuple.
Solution
Explanation to Solution:
*args: The*operator allows the function to receive a tuple containing all positional arguments.- The Loop: Since
argsis a tuple, we usefor i in args:to “unpack” each individual value and print it on a new line. - Flexibility: This prevents “TypeErrors” that usually occur if you provide more arguments than the function was strictly defined to handle.
Exercise 3. Return Multiple Values from a Function
Practice Problem: Write a function calculation() that accepts two variables and calculates both addition and subtraction. The function must return both results in a single return statement.
Exercise Purpose: Unlike many languages (like C or Java) where a function typically returns only one value, Python allows “Tuple Unpacking.” This makes it incredibly efficient to retrieve multiple pieces of processed data at once.
Given Input:
a = 40
b = 10Code language: Python (python)
Expected Output: 50, 30
Hint
- Use a comma to separate your return values:
return add, sub. - When calling the function, you can assign the result to two variables at once.
Solution
Explanation to Solution:
return addition, subtraction: Python implicitly wraps these two values into a tuple.- Result Handling: When you print
res, you see(50, 30). - Unpacking (Optional): You could also write
add, sub = calculation(40, 10), which would assign 50 toaddand 30 tosubdirectly.
Exercise 4. Function with Default Argument
Practice Problem: Create a function show_employee() that accepts an employee’s name and salary. If the salary is not provided in the function call, the function should automatically assign a default value of 9000.
Exercise Purpose: Default arguments are essential for creating APIs or functions where certain settings are “standard.” It allows the function to be called with less information, making the code cleaner and reducing errors when data is missing.
Given Input:
Case 1: name="Ben", salary=12000
Case 2: name="Jessa" (salary missing)Code language: Python (python)
Expected Output:
Name: Ben salary: 12000
Name: Jessa salary: 9000
Hint
- In the function definition, assign the value directly to the parameter:
def show_employee(name, salary=9000):.
Solution
Explanation to Solution:
salary=9000: This is the default parameter. If the caller provides a value, this 9000 is overwritten. If they don’t, 9000 is used.- Positional Rules: Note that default arguments must always come after non-default arguments in the function definition.
- Clean Code: This allows “Jessa” to be processed without the program crashing for a “missing argument.”
Exercise 5. Create an Inner Function
Practice Problem: Create an outer function that accepts two parameters, a and b. Inside, create an inner function that calculates the addition of a and b. The outer function should then add 5 to that sum and return the final result.
Exercise Purpose: This introduces “Nested Functions” and “Encapsulation.” Inner functions are hidden from the global scope, meaning they can only be accessed by the outer function. This is the first step toward understanding Python Decorators and Closures.
Given Input:
a = 5
b = 10Code language: Python (python)
Expected Output: 20
Hint
- The inner function can access the variables
aandbfrom the outer function’s scope. - Call the inner function from within the outer function’s body.
Solution
Explanation to Solution:
- Scope: The
addition()function only exists whileouter_func()is running. You cannot calladdition()from the main part of your script. - Logical Layering: The inner function handles the “pure” math (a+b), while the outer function handles the “business logic” (+5).
- Return Chain: The result of the inner function is passed back to the outer function, which then does one last operation before sending the final answer to the user.
Exercise 6. Create a Recursive Function
Practice Problem: Write a recursive function addition() that calculates the sum of numbers from 0 to 10. A recursive function is a function that calls itself to solve smaller instances of the same problem.
Exercise Purpose: Recursion is a fundamental computer science concept used to solve complex problems by breaking them into simpler sub-problems. It is essential for understanding algorithms like tree traversals and sorting. This exercise focuses on the “Base Case” (when to stop) and the “Recursive Case” (how to progress).
Given Input: num = 10
Expected Output: 55
Hint
Inside the function, check if the number is greater than 0. If it is, return the current number plus a call to the same function with num - 1. If it’s 0, return 0 to stop the recursion.
Solution
Explanation to Solution:
- The Base Case (
if num:elsereturn 0): This is the “emergency exit.” Without it, the function would call itself forever, leading to a “RecursionError.” - The Recursive Call:
num + addition(num - 1)pauses the current operation to wait for the result of the next one. For 10, it looks like:10 + (9 + (8 + ... + (0))). - Unwinding the Stack: Once the function reaches 0, it begins adding the numbers back up the chain until it reaches the original call.
Exercise 7. Assign a Different Name to Function and Call It
Practice Problem: Assign a different name to the function display_student(name, age) and call it using the new name. For example, assign it to a variable called show_student.
Exercise Purpose: In Python, functions are “first-class objects.” This means they can be treated like any other variable—passed as arguments, returned from other functions, or renamed. This is useful for aliasing long function names or passing logic into different modules.
Given Input:
def display_student(name, age):
print(name, age)Code language: Python (python)
Expected Output:
Emma 26
Hint
- In Python, you can assign a function to a variable without parentheses:
new_name = original_name. - If you use parentheses, you are assigning the result of the function, not the function itself.
Solution
Explanation to Solution:
- Function as Object:
show_student = display_studentcreates a second reference to the same piece of code in memory. - No Parentheses: By omitting
(), we tell Python “give me the function itself,” not “run the function and give me the output.” - Alias: This allows the program to use
show_studentexactly like the originaldisplay_student.
Exercise 8. Generate a List of Even Numbers (Range Function)
Practice Problem: Create a function that generates a list of all even numbers between 4 and 30.
Exercise Purpose: This exercise teaches the use of the range() function and how to convert range objects into lists. Understanding how to generate sequences of data is vital for data processing and automated loops.
Expected Output:
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
Hint
- Use
range(start, stop, step). To get even numbers, set thestepparameter to 2. - Remember that the
stopvalue in a range is exclusive (it goes up to but does not include that number).
Solution
Explanation to Solution:
range(4, 30, 2): This generates numbers starting at 4, ending before 30, incrementing by 2 every time.list()constructor: Arangeis a generator object (it doesn’t store all numbers in memory at once). We wrap it inlist()to force it to create an actual list of items for printing.- Exclusion Rule: Since the problem asks for numbers between 4 and 30, 30 is typically excluded.
Exercise 9. Find the Largest Item in a List
Practice Problem: Create a function that takes a list of numbers as input and returns the largest item from that list without using the built-in max() function (to practice manual logic).
Exercise Purpose: Finding a maximum value is one of the most common tasks in programming (e.g., finding the highest price, the top score, or the oldest record). Implementing this manually builds an understanding of “Accumulator Patterns”—keeping track of a state while iterating through data.
Given Input: x = [4, 6, 8, 24, 12, 2]
Expected Output: 24
Hint
- Initialize a variable with the first element of the list.
- Use a
forloop to compare every other number in the list to this variable. If you find a larger number, update your variable.
Solution
Explanation to Solution:
- Initialization: By setting
largest = list_input[0], we have a starting point for comparison. - Comparison Logic: The
if num > largestcheck acts as a filter. Every time a “new champion” is found, thelargestvariable is updated. - O(n) Complexity: The function looks at each item exactly once, making it efficient for lists of any size.
Exercise 10. Call Function using Positional and Keyword Arguments
Practice Problem: Define a function describe_pet(animal_type, pet_name) that prints a description of a pet. Call this function twice: once using positional arguments and once using keyword arguments.
Exercise Purpose: This exercise demonstrates the flexibility of Python’s calling conventions. Positional arguments rely on the order of the data, while Keyword arguments use the parameter names to ensure data goes to the right place regardless of order.
Given Input:
# Call 1 (Positional): "hamster", "Harry"
# Call 2 (Keyword): animal_type="dog", pet_name="Willie"Code language: Python (python)
Expected Output:
I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Willie.
Hint
- When using positional arguments, “hamster” must come first to match
animal_type. - With keyword arguments, you can actually swap the order (e.g.,
pet_name="Willie", animal_type="dog") and it will still work perfectly.
Solution
Explanation to Solution:
- Positional Call: Python maps “hamster” to
animal_typebecause it is the first argument provided. - Keyword Call: By explicitly stating
animal_type="dog", we tell Python exactly where the data belongs. This makes the code more readable and less prone to “swapped data” bugs. - Consistency: Both methods execute the same logic inside the function; they just differ in how they “hand off” the data.
Exercise 11. Create a Function with Keyword Arguments
Practice Problem: Create a function print_info(**kwargs) that accepts an arbitrary number of keyword arguments and prints the key-value pairs.
Exercise Purpose: While *args handles a list of values, **kwargs (keyword arguments) handles named data as a dictionary. This is standard practice in Python for functions that need to handle optional configuration settings or metadata.
The exercise requires you to create a function that can accept any number of keyword arguments. A keyword argument is where you specify the name of the argument along with its value (e.g., name="Alice", age=30). Inside the function, you need to access these arguments and print them in a key-value format.
Given Input: print_info(name="Alice", age=30, city="New York")
Expected Output:
name: Alice
age: 30
city: New York
Hint
- Use two asterisks
**before the parameter name. This tells Python to collect all named arguments into a dictionary. - You can then use
.items()to loop through the keys and values.
Solution
Explanation to Solution:
**kwargs: The double asterisk “packs” the arguments into a dictionary calledkwargs.kwargs.items(): This method allows us to iterate through both the label (key) and the data (value) simultaneously.- Infinite Scalability: You could pass 100 different arguments to this function, and it would handle all of them without needing 100 predefined parameters.
Exercise 12. Modifying Global Variables
Practice Problem: Define a global variable global_var = 10. Write a function that successfully changes the value of this global variable to 20.
Exercise Purpose: Normally, variables created inside a function are “Local”—they disappear when the function ends. To modify a variable that lives outside the function, you must use the global keyword. This exercise teaches you how to manage data persistence across different parts of your program.
Given Input: global_var = 10
Expected Output:
Initial: 10
Modified: 20
Hint
- If you just write
global_var = 20inside the function, Python creates a new local variable with that name. - You must declare
global global_varat the start of the function to tell Python you want to use the one from the outside.
Solution
Explanation to Solution:
global global_var: This line is a “permission slip.” It tells the function, “Don’t create a new variable; use the one that already exists in the main script.”- Assignment: Once the global link is established, changing the value inside the function updates it for the entire program.
- Caution: Use global variables sparingly; overusing them can make debugging difficult because any function could be changing your data at any time.
Exercise 13. Recursive Factorial (Non-Negative Integers)
Practice Problem: Write a recursive function to calculate the factorial of a non-negative integer.
Exercise Purpose: Factorials (5! = 5 * 4 * 3 * 2 * 1) are the textbook example of recursion. This exercise reinforces the concept of a “Base Case” (stopping at 1) to prevent the function from running forever and crashing the memory stack.
Given Input: number = 5
Expected Output: The factorial of 5 is 120
Hint
- Remember that 0! is 1. Your base case should handle n <=1.
- The recursive step is
n * factorial (n-1).
Solution
Explanation to Solution:
- The Chain: When you call
recur_factorial(5), it returns5 * recur_factorial(4), which returns4 * recur_factorial(3), and so on. - The Bottom: Eventually, it hits
recur_factorial(1), which returns1. - The Multiplier: Now Python “unwinds” the stack, multiplying all those returned values together (1*2*3*4*5) to get 120.
Exercise 14. Create a Lambda Function to Square a Number
Practice Problem: Use the lambda keyword to create a small, anonymous function that takes one number and returns its square.
Exercise Purpose: Sometimes you need a simple function for a split second (like when sorting a list or filtering data) and don’t want to write a full def block. Lambda functions are “one-liners” that make your code more concise and “Pythonic.”
Given Input: number = 5
Expected Output: 25
Hint
- The syntax is
lambda arguments: expression. - You don’t use a
returnstatement; the result of the expression is returned automatically.
Solution
Explanation to Solution:
lambda x:: This defines the input variable.x * x: This is the operation. Notice there is no name and nodefkeyword.- Anonymity: While we assigned it to
square_numhere for clarity, lambdas are often used directly inside other functions likemap()orfilter()without ever being given a name.
Exercise 15. Filter a List Using Lambda and filter()
Practice Problem: Use the filter() function combined with a lambda to extract all even numbers from the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
Exercise Purpose: The filter() function is a specialized tool for “weeding out” data. Instead of writing a bulky for loop with an if statement, filter() allows you to define a “rule” (the lambda) and apply it to an entire collection. This is a core concept in data science for cleaning datasets.
Given Input: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Expected Output: [2, 4, 6, 8, 10]
Hint
- The
filter()function takes two arguments: the condition function and the list. - The condition should return
Truefor numbers you want to keep. - Remember to wrap the result in
list()to see the final output!
Solution
Explanation to Solution:
lambda x: x % 2 == 0: This is our filter “gatekeeper.” If a number divided by 2 has a remainder of 0, the gate opens and the number stays.- The “Lazy” Filter:
filter()returns an iterator (a promise to calculate the values) rather than a list. We uselist()to force Python to actually generate the numbers so we can print them. - Efficiency: This method is often faster and much more readable than manually appending items to a new list.
Exercise 16. Transform a List Using Lambda and map()
Practice Problem: Use the map() function and a lambda to double every element in the list [1, 2, 3, 4, 5].
Exercise Purpose: While filter removes items, map transforms them. It applies a specific operation to every single item in a list simultaneously. It’s like an assembly line where every item gets the same “upgrade” as it passes through.
Given Input: numbers = [1, 2, 3, 4, 5]
Expected Output: [2, 4, 6, 8, 10]
Hint
- Think of
mapas “mapping” an old value to a new value. - The syntax is
map(lambda_expression, list).
Solution
Explanation to Solution:
lambda x: x * 2: This is the transformation rule. Everyxthat goes in comes out asx * 2.- One-to-One Mapping: Unlike
filter, the output ofmapwill always be the same length as the input. - Declarative Style: You are telling Python what you want (doubled numbers) rather than how to loop through and do it, which is the hallmark of professional Python code.
Exercise 17. Sort Complex Data with sorted() and Lambda
Practice Problem: You have a list of tuples representing students and their grades: [("Alice", 88), ("Bob", 75), ("Charlie", 92)]. Use the sorted() function and a lambda to sort this list based on the grades (the second element) in ascending order.
Exercise Purpose: Real-world data is rarely just a simple list of numbers; it’s usually “messy” objects or tuples. This exercise teaches you how to tell Python exactly which part of a complex object it should use for sorting.
Given Input: students = [("Alice", 88), ("Bob", 75), ("Charlie", 92)]
Expected Output: [('Bob', 75), ('Alice', 88), ('Charlie', 92)]
Hint
- The
sorted()function has akeyparameter. - Assign a lambda to this key that points to the index you want to sort by:
key=lambda item: item[1].
Solution
Explanation to Solution:
key=lambda student: student[1]: This tells the sorting algorithm: “When comparing two students, don’t look at their names (index 0). Look at their grades (index 1).”- Stability: Python’s
sorted()function is highly efficient and maintains the original order of items if their grades are identical. - Versatility: By changing the index to
0, you could easily switch back to sorting alphabetically.
Exercise 18. Create a Higher-Order Function
Practice Problem: Write a function apply_operation(func, x, y) that takes another function (func) and two numbers (x, y) as arguments. It should return the result of calling func(x, y). Show how this works by passing in different operations like addition and multiplication.
Exercise Purpose: This is where you truly become a Python “Power User.” A Higher-Order Function is a function that treats other functions as parameters. This allows you to write extremely generic code that can do anything depending on what logic you “plug into” it.
Given Input:
# Function 1: add(a, b)
# Function 2: multiply(a, b)
# Values: 5, 3Code language: Python (python)
Expected Output:
Addition Result: 8
Multiplication Result: 15
Hint
Inside apply_operation, you don’t need to know what func does. Just call it like a normal function: return func(x, y).
Solution
Explanation to Solution:
- Function Injection: We are “injecting” the
addormultiplylogic intoapply_operation. - Abstraction:
apply_operationdoesn’t care if it’s adding, subtracting, or sending an email; it just executes the “callback” function it was given. - Decoupling: This separates the execution (when to run the code) from the logic (what the code actually does), which is essential for building large, maintainable software systems.
