Python Functions Exercises
Python Functions Practice Questions
Why do we use functions in Python programs?
Functions are mainly used to make programs more reusable, organized, and easier to maintain. Instead of repeating the same code multiple times, we can place it inside a function and call it whenever required.
- Option 1: Correct – Functions improve readability, maintainability, and reduce duplication.
- Option 2: Incorrect – Data storage is handled by data structures like lists, sets, or dictionaries, not functions.
- Option 3: Incorrect – Functions don’t inherently speed up execution; they organize logic.
- Option 4: Incorrect – Variables are still needed inside or outside functions.
Key takeaway: Functions help us write clean, structured, and reusable code.
Which of the following is the correct way to define a Python function that prints "Hello World"?
This question tests the basic syntax of defining a function in Python:
- Option 1: Incorrect –
functionis not a Python keyword. - Option 2: Incorrect – Missing parentheses
()in function definition. - Option 3: Incorrect – Python uses
print(), notecho. - Option 4: Correct –
defkeyword, parentheses, andprint()used correctly.
Key takeaway: Always use def function_name(): to define a function in Python, and ensure parentheses are included even if there are no parameters.
Which of the following is the correct way to call a Python function named greet?
This question checks the correct syntax for calling a Python function:
- Option 1: Incorrect –
callis not used in Python. - Option 2: Incorrect – This only references the function object, it does not execute it.
- Option 3: Incorrect – Square brackets
[]are used for lists or indexing, not function calls. - Option 4: Correct – Parentheses
()are required to call the function.
Key takeaway: Always use parentheses when calling a function in Python, even if it does not take any parameters.
Which statement correctly describes the syntax for defining a Python function?
In Python, functions are defined using the keyword def, followed by the function name and parentheses. The parentheses may include parameters if needed, and the function body is indented.
- Option 1: Incorrect –
funcis not a Python keyword. - Option 2: Incorrect –
defineis not used in Python. - Option 3: Correct –
def function_name():is the proper syntax. - Option 4: Incorrect – Function names alone without
defcannot define a function.
Key takeaway: Always start a function definition in Python with the def keyword followed by parentheses, even if there are no parameters.
Which of the following functions correctly returns the value 10?
This question tests understanding of returning values from functions in Python:
- Option 1: Incorrect –
print(10)outputs the value but does not return it. - Option 2: Incorrect – Returns a string "10" instead of integer 10.
- Option 3: Incorrect – Writing
10alone inside a function does nothing; it must usereturn. - Option 4: Correct –
return 10correctly returns the integer value 10.
Key takeaway: Use return inside a function to send a value back to the caller. print() only displays it on the screen and does not return it.
Which of the following calls to the function greet(name, age) correctly uses keyword arguments?
This question focuses on the difference between positional and keyword arguments:
- Option 1: Incorrect – Uses positional arguments only.
- Option 2: Correct – Both arguments are passed by name, so order does not matter.
- Option 3: Partially correct – First argument is positional, second is keyword. Python allows it, but fully keyword form is Option 2.
- Option 4: Incorrect – Positional argument cannot follow a keyword argument; this causes a syntax error.
Key takeaway: Keyword arguments allow passing values by name, improving readability and avoiding errors related to argument order.
Which of the following function definitions correctly uses a default parameter value for greeting?
This question tests understanding of default parameter values in Python functions:
- Option 1: Incorrect – No default value is provided for
greeting. - Option 2: Incorrect – The order of print arguments is reversed (minor issue) and can be confusing. Prefer standard format.
- Option 3: Incorrect – Non-default parameter
greetingcannot follow a parameter with a default valuename="John". - Option 4: Correct – Default value is assigned properly, and positional arguments come before default parameters.
Key takeaway: In Python, parameters with default values should come after positional parameters. Default values are used when arguments are not provided by the caller.
Which function definition correctly accepts a variable number of positional arguments?
This question tests understanding of variable-length positional arguments using *args:
- Option 1: Correct – The
*argssyntax allows the function to accept any number of positional arguments as a tuple. - Option 2: Incorrect – Only accepts a single argument; cannot handle multiple numbers directly.
- Option 3: Incorrect –
**argsis used for keyword arguments, not positional arguments. - Option 4: Incorrect –
*kwargsis invalid;kwargsconventionally refers to keyword arguments (**kwargs).
Key takeaway: Use *args when you want a function to accept an arbitrary number of positional arguments. It is stored as a tuple inside the function.
Which function definition correctly accepts a variable number of keyword arguments?
This question tests understanding of variable-length keyword arguments using **kwargs:
- Option 1: Correct – The
**kwargssyntax collects all keyword arguments into a dictionary, allowing iteration withitems(). - Option 2: Incorrect –
*kwargscollects positional arguments, not keyword arguments. - Option 3: Incorrect – Only accepts a single dictionary argument; does not accept arbitrary keyword arguments directly.
- Option 4: Incorrect –
*argscollects positional arguments; usingitems()on it will cause an error.
Key takeaway: Use **kwargs when you want a function to accept an arbitrary number of keyword arguments. They are stored as a dictionary inside the function.
Which of the following calls correctly uses positional, default, and keyword arguments for the function:
def greet(name, age=25, city="Unknown"):
print(f"{name}, {age}, {city}")
This question tests understanding of mixing positional, default, and keyword arguments in Python functions:
- Option 1: Incorrect – Positional argument
"Alice"cannot follow a keyword argumentage=30; this causes a syntax error. - Option 2: Incorrect – Positional argument
30cannot follow keyword argumentcity="New York". - Option 3: Correct – Positional argument
"Alice"comes first, then keyword argumentsage=30andcity="New York". - Option 4: Incorrect – Positional argument
30cannot follow keyword argumentname="Alice".
Key takeaway: In Python, positional arguments must come first, followed by default or keyword arguments. Mixing them correctly avoids syntax errors and ensures clarity.
Which of the following functions correctly returns multiple values that can be unpacked?
This question tests understanding of returning multiple values and tuple unpacking in Python:
- Option 1: Incorrect – Returns a
list, which cannot be unpacked into multiple variables without indexing. - Option 2: Correct – Returns a tuple implicitly (
10, 20, 30) that can be unpacked intoa, b, c. - Option 3: Incorrect –
print()outputs values but does not return them, so unpacking fails. - Option 4: Incorrect – Returns a single integer (10), cannot unpack into three variables.
Key takeaway: Python functions can return multiple values as tuples. These tuples can be unpacked into separate variables directly for easy access.
Which of the following examples correctly demonstrates modifying a global variable inside a function?
This question tests understanding of local vs global scope in Python functions:
- Option 1: Incorrect – Modifying a global variable without
globalcauses anUnboundLocalError. - Option 2: Incorrect – Same issue as Option 1; assignment creates a local variable by default.
- Option 3: Incorrect –
localis not a Python keyword; this will cause a syntax error. - Option 4: Correct – Using
global countallows the function to modify the global variable.
Key takeaway: To modify a global variable inside a function, you must declare it as global. Otherwise, Python treats the variable as local within the function.
Which of the following correctly defines a nested function and calls it from the outer function?
This question tests understanding of nested functions in Python:
- Option 1: Incorrect –
inner()is called outsideouter(), so it is not in scope. - Option 2: Incorrect – Calling
outer.inner()is invalid in Python; nested functions are not attributes. - Option 3: Incorrect – Returns the inner function, but it is never called inside
outer(). - Option 4: Correct –
inner()is defined and called insideouter(), thenouter()is called to execute both.
Key takeaway: Nested functions are functions defined inside other functions. They are only accessible within the scope of the outer function.
Which statement correctly describes first-class functions in Python?
This question tests understanding of first-class functions in Python:
- Option 1: Incorrect – Functions can be defined anywhere, not just inside classes.
- Option 2: Incorrect – Functions can be assigned to variables in Python.
- Option 3: Correct – Python treats functions as objects, allowing them to be passed as arguments, returned from other functions, and assigned to variables.
- Option 4: Incorrect – Functions do not need to return a value to be considered first-class.
Key takeaway: In Python, functions are first-class objects, enabling higher-order programming patterns like passing functions as arguments, returning them, and storing them in variables.
Which of the following correctly defines a lambda function to add two numbers?
This question tests understanding of lambda (anonymous) functions in Python:
- Option 1: Incorrect – Syntax is invalid; you cannot use
defwith= lambda. - Option 2: Incorrect – Lambda does not use
returnor parentheses like this. - Option 3: Incorrect –
functionis not a Python keyword. - Option 4: Correct –
lambda x, y: x + ydefines an anonymous function assigned toadd.
Key takeaway: Lambda functions are concise, single-expression functions. They do not use def or return and are often used for short operations or as arguments to higher-order functions.
Which of the following functions correctly implements recursion to calculate the factorial of a number?
This question tests understanding of recursive functions in Python:
- Option 1: Correct – Proper base case (
n == 0) prevents infinite recursion. The function multipliesnby the factorial ofn-1. - Option 2: Incorrect – This uses iteration, not recursion.
- Option 3: Incorrect – Base case returns 0, so factorial(0) = 0, which is wrong.
- Option 4: Incorrect – Calls itself with the same
nendlessly, causing infinite recursion.
Key takeaway: Recursive functions require a base case to stop recursion. Each recursive call should move toward this base case to avoid infinite loops.
Which of the following correctly demonstrates a closure in Python?
This question tests understanding of closures in Python:
- Option 1: Incorrect – The inner function does not reference the outer function’s parameter, so it is not a closure.
- Option 2: Correct – The inner function references
xfrom the enclosing scope, forming a closure. Callingf(5)uses the value ofxpreserved fromouter(10). - Option 3: Incorrect – No inner function; not a closure.
- Option 4: Incorrect – The inner function is not returned; no closure is formed.
Key takeaway: A closure occurs when an inner function remembers and uses variables from its enclosing function even after the outer function has finished executing.
Which of the following correctly defines and uses a decorator in Python?
This question tests understanding of decorators in Python:
- Option 1: Incorrect – The decorator does not return a wrapper function; it only calls the function once.
- Option 2: Incorrect – Decorator must return a function; this code only prints text, it does not wrap the original function.
- Option 3: Correct – Defines a
wrapperfunction inside the decorator, adds behavior before and after callingfunc, returnswrapper, and uses@decoratorsyntax correctly. - Option 4: Incorrect – The decorator incorrectly tries to call
funcimmediately and does not return a wrapper.
Key takeaway: A decorator is a function that wraps another function to modify its behavior. The decorator must return a function, and the @decorator syntax applies it to the target function.
What will be the output of the following recursive function call?
def countdown(n):
if n <= 0:
return
print(n)
countdown(n-2)
countdown(5)
This question tests understanding of recursive calls with modified step sizes:
- Option 1: Incorrect – This would be correct if the function decreased by 1, but it decreases by 2.
- Option 2: Correct – Function prints
n, then calls itself withn-2, producing 5 → 3 → 1. Option 3: Incorrect – The function stops whenn <= 0, so -1 is not printed.Option 4: Incorrect – This would happen if the function decreased by 1 and stopped before 0.
Key takeaway: Carefully track the recursive call changes and base case to predict the correct sequence of outputs. Step sizes affect the printed values.
What will be the output of the following function call?
def func(a, *args, **kwargs):
print(a, args, kwargs)
func(1, 2, 3, x=4, y=5)
This question tests understanding of positional, *args, and **kwargs in Python functions:
- Option 1: Correct –
areceives the first positional argument (1),*argscollects remaining positional arguments as a tuple (2, 3), and**kwargscollects keyword arguments as a dictionary. - Option 2: Incorrect –
*argsis always a tuple, not a list. - Option 3: Incorrect – Positional arguments beyond the first are not printed individually;
argsgroups them as a tuple. - Option 4: Incorrect – Same issue;
*argsmust be a tuple.
Key takeaway: In Python, *args collects extra positional arguments as a tuple, and **kwargs collects keyword arguments as a dictionary. Understanding this helps in designing flexible functions.
Explore More Python Exercises
You may also like these Python exercises:
Test Your Python Functions Knowledge
Practicing Python Functions? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python – Functions
In Python, functions are one of the most important building blocks of any program. They let us group code into reusable pieces, making our programs easier to read, test, and maintain. In this section on Solviyo, we’ll be working through exercises that help you get comfortable with creating and using functions in real coding scenarios.
If you’ve ever found yourself writing the same code over and over again, a function is the solution. Instead of repeating yourself, you define the code once inside a function, and then call it whenever you need it. We’ll start with simple exercises like writing a function that adds two numbers, and then move into more practical problems where you pass parameters, return results, and handle multiple inputs.
But functions in Python go far beyond the basics. You’ll also practice writing functions with default arguments, using variable-length arguments with *args and **kwargs, and even returning more than one value at a time. We’ll also introduce lambda functions, which are quick, one-line functions that are perfect for cases where you don’t want the overhead of a full definition.
Another key part of this section is understanding scope. We’ll look at local and global variables, so you know exactly where your data “lives” when working with functions. It’s a small detail that can cause big headaches if you don’t get it right, but with practice, you’ll handle it like second nature.
To make things interesting, the exercises in this section aren’t just theory-based. You’ll build small, practical programs that use functions to organize the logic. Think of calculators, string formatters, or even data processors where you split a big task into smaller, reusable chunks. These real-world-style problems will help you see how functions make your code cleaner and easier to manage.
At Solviyo, our goal is to keep practice engaging and useful. Each exercise in the Functions section is designed to push you a little further than the last. We also highlight common mistakes—like forgetting to return a value, misusing default parameters, or accidentally mixing up local and global scope—so you can avoid them in your own projects.
By the end of this section, you’ll be confident in writing and using functions in Python. You’ll not only understand the syntax but also know how to apply functions effectively to structure real applications. Let’s get started and make functions your strongest coding tool yet.