A Python function is a block of code or a group of statements designed to perform a specific task. Functions are valuable for code reusability, allowing you to execute the same logic whenever needed without writing it multiple times.
This exercise on Python functions aims to help developers learn and practice defining functions, function calls, function arguments, inner functions, and built-in functions. Let us know in the comment section below if you have any alternative solutions. It will help other developers.
Also Read:
This exercise includes the following: –
- It contains Python function assignments, programs, questions, and challenges.
- Total 18 questions. The solution is provided for all questions and tested on Python 3.
Use Online Code Editor to solve exercise questions.
Table of contents
- Exercise 1: Create a function in Python
- Exercise 2: Create a function with variable length of arguments
- Exercise 3: Return multiple values from a function
- Exercise 4: Create a function with a 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 through the new name
- Exercise 8: Generate a Python list of all the even numbers between 4 to 30
- Exercise 9: Find the largest item from list
- Exercise 10: Call Function using both positional and keyword arguments
- Exercise 11: Create a function with keyword arguments
- Exercise 12: Modifies global variable
- Exercise 13: Write a recursive function to calculate the factorial
- Exercise 14: Create a lambda function that squares a given number
- Exercise 15: Use a lambda with the filter() function to get all even numbers from a list
- Exercise 16: Use a lambda with the map() function to double each element in a list
- Exercise 17: Use a lambda with the sorted() function to sort a list of tuples based on the second element
- Exercise 18: Create Higher-Order Function
Exercise 1: Create a function in Python
Write a program to create a function that takes two arguments, name and age, and prints their values.
Show Hint
- Use the
def
keyword followed by the function name to define the function - Next, define two parameters within the function’s parentheses.
- Print these parameters using the
print()
function inside the function’s body. - Finally, call the function by passing the name and age as arguments.
Show Solution
Exercise 2: Create a function with variable length of arguments
Write a program to create a function func1()
that accepts a variable number of arguments and prints each of their values.
Note: Create this function so that it can receive any number of arguments, process them, and display the value of each individual argument.
Read: variable length of arguments in functions
Function call:
# call function with 3 arguments
func1(20, 40, 60)
# call function with 2 arguments
func1(80, 100)
Code language: Python (python)
Expected Output:
Printing values
20
40
60
Printing values
80
100
Show Hint
To accept a variable number of positional arguments, allowing functions to take any quantity of these arguments, we use *args
as a parameter. (This involves prefixing a parameter name with an asterisk: *
).
Using *args
, you can pass any number of positional arguments to the function. Internally, all these passed values are collected and represented as a tuple.
Show Solution
Exercise 3: Return multiple values from a function
Write a function calculation()
that accepts two variables and calculates both their addition and subtraction. The function should then return both the sum and the difference in a single return statement.
Given:
def calculation(a, b):
# Your Code
res = calculation(40, 10)
print(res)
Code language: Python (python)
Expected Output
50, 30
Expected Output:
Show Hint
In Python, to return multiple values from a function, separate the values with commas in the return
statement
Show Solution
Python allows you to return multiple values from a function by separating them with commas in the return
statement
Solution 1:
Solution 2:
Exercise 4: Create a function with a default argument
Write a program to create a function show_employee()
with the following specifications:
- It should accept the employee’s name and salary.
- It should display both the name and salary.
- If the salary is not provided in the function call, it should default to 9000.
See: Default arguments in function
Given:
showEmployee("Ben", 12000)
showEmployee("Jessa")
Code language: Python (python)
Expected output:
Name: Ben salary: 12000 Name: Jessa salary: 9000
Show Hint
Default arguments in Python will assume their default value during a function call if no corresponding argument is explicitly provided. You can assign a default value to a function parameter in the function definition using the assignment operator (=
).
Show Solution
Exercise 5: Create an inner function
Create a program with nested functions to perform an addition calculation as follows:
- Define an outer function that accepts two parameters,
a
andb
. - Inside this outer function, define an inner function that calculates the sum of
a
andb
. - The outer function should then add 5 to this sum.
- Finally, the outer function should return the resulting value.”
Show Solution
In Python, you can define a function inside another function, creating a nested function. Nested functions can be useful for performing complex tasks multiple times within their enclosing function or for reducing the need for loops and preventing code duplication.
Exercise 6: Create a recursive function
Write a program to create a recursive function that calculates the sum of numbers from 0 to 10.
A recursive function is a function that calls itself repeatedly.
Expected Output:
55
Show Solution
Exercise 7: Assign a different name to function and call it through the new name
Below is the function display_student(name, age)
. Assign a new name show_student(name, age)
to it and call it using the new name.
Given:
def display_student(name, age):
print(name, age)
display_student("Emma", 26)
Code language: Python (python)
You should be able to call the same function using
show_student(name, age)
Code language: Python (python)
Show Hint
Assign a different name to function using the assignment (=) operator. To assign a different name to an existing function and then call it using this new name, you can simply assign the function object to a new variable.
fun_name = new_name
Show Solution
Exercise 8: Generate a Python list of all the even numbers between 4 to 30
Expected Output:
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
Show Hint
- Use the built-in range() function to generate a sequence of numbers from the given start number up to (but not including) the stop number, with a step of 2, to obtain even numbers.
- Pass the result of the
range()
function to thelist()
constructor to create a list
Show Solution
Exercise 9: Find the largest item from list
Given:
x = [4, 6, 8, 24, 12, 2]
Code language: Python (python)
Expected Output:
24
Show Hint
Use the built-in function max()
to get the largest number from a list
Show Solution
Exercise 10: Call Function using both positional and keyword arguments
Define a function describe_pet(animal_type, pet_name)
that prints a description of a pet. Call this function using both positional and keyword arguments.
+ Hint
Call the function twice: once by just giving the values in order, and once by saying animal_type=
and pet_name=
.
+ Show Solution
Steps to solve this question:
Exercise 11: Create a function with keyword arguments
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.
Create a function print_info(**kwargs)
that accepts keyword arguments and prints the key-value pairs. Call it with different keyword arguments
+ Hint
- Inside, iterate through the
kwargs
dictionary with afor
loop and.items()
, printing eachkey
andvalue
. - Call the function a few times with different
key=value
pairs.
+ Show Solution
Steps to solve this question:
Exercise 12: Modifies global variable
Define a global variable global_var = 10. Write a function that modifies a global variable value.
+ Hint
Use global
keyword to create and modify the global variable value
+ Show Solution
Exercise 13: Write a recursive function to calculate the factorial
Write a recursive function to calculate the factorial of a non-negative integer.
+ Hint
- Base Case: The function needs a condition to stop calling itself. What is the factorial of 0?
- Recursive Step: If
n
is not 0, the factorial ofn
isn
times the factorial of what? - Function Call: The function should call itself with a modified argument.
+ Show Solution
Exercise 14: Create a lambda function that squares a given number
A lambda function in Python is a small anonymous function defined using the lambda
keyword. The syntax is lambda arguments: expression
. The expression
is evaluated and returned.
+ Show Solution
Exercise 15: Use a lambda with the filter()
function to get all even numbers from a list
Given:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Code language: Python (python)
Expected Output:
The even numbers in the list are: [2, 4, 6, 8, 10]
+ Hint
The filter()
function takes two arguments: a function and an iterable. It applies the function to each element of the iterable and returns an iterator containing only the elements for which the function returns True
.
A lambda function can be used as the first argument to define a filtering condition concisely.
+ Show Solution
Exercise 16: Use a lambda with the map()
function to double each element in a list
Given:
numbers = [1, 2, 3, 4, 5]
Code language: Python (python)
Expected Output:
The doubled numbers are: [2, 4, 6, 8, 10]
+ Hint
The map()
function applies a given function to each item of an iterable (like a list) and returns an iterator of the results. You can use a lambda function to define the operation to be performed on each element concisely.
+ Show Solution
Exercise 17: Use a lambda with the sorted()
function to sort a list of tuples based on the second element
Given:
data = [('apple', 5), ('banana', 2), ('cherry', 8), ('date', 1)]
Code language: Python (python)
Expected Output:
The sorted list of tuples based on the second element is: [('date', 1), ('banana', 2), ('apple', 5), ('cherry', 8)]
+ Hint
The sorted()
function can take a key
argument, which is a function that will be called on each element of the list prior to making comparisons.
A lambda function can be used here to specify that the sorting should be based on the element at index 1 of each tuple.
+ Show Solution
Exercise 18: Create Higher-Order Function
Write a function apply_operation(func, x, y)
that takes a function func
and two numbers x
and y
as arguments, and returns the result of calling func(x, y)
. Demonstrate its use with different functions (e.g., addition, subtraction).
The exercise requires you to create a higher-order function, which is a function that can take other functions as arguments.
+ Hint
The apply_operation
function takes a function func
as its first argument and then calls this function with the provided numbers x
and y
. You can define the functions to be passed to apply_operation
using either regular function definitions (def
) or lambda functions for more concise operations.