PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python Exercises » Python Functions Exercise

Python Functions Exercise

Updated on: May 22, 2025 | 163 Comments

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:

  • Python Functions Quiz
  • Python functions and Python function arguments to solve questions
  • Python Functions and Modules Interview Questions

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
# demo is the function name
def demo(name, age):
    # print value
    print(name, age)

# call function
demo("Ben", 25)Code language: Python (python)

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
def func1(*args):
  for arg in args:
    print(arg)

# Example calls to the function with different numbers of arguments
func1(10, 20)
func1("hello", 3.14, True)
func1(1, 2, 3, 4, 5)
func1() # Calling with no argumentsCode language: Python (python)

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:

def calculation(a, b):
    addition = a + b
    subtraction = a - b
    # return multiple values separated by comma
    return addition, subtraction

# get result in tuple format
res = calculation(40, 10)
print(res)Code language: Python (python)

Solution 2:

def calculation(a, b):
    return a + b, a - b

# get result in tuple format
# unpack tuple
add, sub = calculation(40, 10)
print(add, sub)Code language: Python (python)

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
# function with default argument
def show_employee(name, salary=9000):
    print("Name:", name, "salary:", salary)

show_employee("Ben", 12000)
show_employee("Jessa")Code language: Python (python)

Exercise 5: Create an inner function

Create a program with nested functions to perform an addition calculation as follows:

  1. Define an outer function that accepts two parameters, a and b.
  2. Inside this outer function, define an inner function that calculates the sum of a and b.
  3. The outer function should then add 5 to this sum.
  4. 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.

# outer function
def outer_fun(a, b):
    square = a ** 2

    # inner function
    def addition(a, b):
        return a + b

    # call inner function from outer function
    add = addition(a, b)
    # add 5 to the result
    return add + 5

result = outer_fun(5, 10)
print(result)Code language: Python (python)

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
def addition(num):
    if num:
        # call same function by reducing number by 1
        return num + addition(num - 1)
    else:
        return 0

res = addition(10)
print(res)Code language: Python (python)

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
def display_student(name, age):
    print(name, age)

# call using original name
display_student("Emma", 26)

# assign new name
showStudent = display_student
# call using new name
showStudent("Emma", 26)Code language: Python (python)

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 the list() constructor to create a list
Show Solution
print(list(range(4, 30, 2)))Code language: Python (python)

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
x = [4, 6, 8, 24, 12, 2]
print(max(x))Code language: Python (python)

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:

def describe_pet(animal_type, pet_name):
  print(f"\nI have a {animal_type} named {pet_name}.")

# Calling the function using positional arguments
describe_pet('hamster', 'Harry')
describe_pet('dog', 'Lucy')

# Calling the function using keyword arguments
describe_pet(animal_type='cat', pet_name='Whiskers')
describe_pet(pet_name='Buddy', animal_type='goldfish')Code language: Python (python)

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 a for loop and .items(), printing each key and value.
  • Call the function a few times with different key=value pairs.
+ Show Solution

Steps to solve this question:

def print_info(**kwargs):
    if kwargs:  # Check if any keyword arguments were passed
        print("\n--- Information ---")
        for key, value in kwargs.items():
            print(f"{key}: {value}")
    else:
        print("\nNo information provided.")

# Example calls to the function
print_info(name="Alice", age=30, city="New York")
print_info(job="Engineer", salary=75000)
print_info(country="USA", state="California", zip_code="90210")
print_info()  # Call with no argumentsCode language: Python (python)

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
global_var = 10

def modify_global_var():
    global global_var
    global_var = 20
    print("Inside function:", global_var)

modify_global_var()
print("Outside function:", global_var)Code language: Python (python)

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 of n is n times the factorial of what?
  • Function Call: The function should call itself with a modified argument.
+ Show Solution
def factorial_recursive(n):
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers")
    elif n == 0:
        return 1  # Base case: factorial of 0 is 1
    else:
        return n * factorial_recursive(n - 1)  # Recursive step

# Example usage:
number = 5
result = factorial_recursive(number)
print(f"The factorial of {number} is {result}")  
# Output: The factorial of 5 is 120
Code language: Python (python)

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
square = lambda x: x**2

# Example usage:
number = 5
squared_number = square(number)
print(f"The square of {number} is {squared_number}")Code language: Python (python)

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
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(f"The even numbers in the list are: {even_numbers}")Code language: Python (python)

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
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(f"The doubled numbers are: {doubled_numbers}")Code language: Python (python)

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
data = [('apple', 5), ('banana', 2), ('cherry', 8), ('date', 1)]
sorted_data = sorted(data, key=lambda item: item[1])
print(f"The sorted list of tuples based on the second element is: {sorted_data}")Code language: Python (python)

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.

+ Show Solution
def apply_operation(func, x, y):
  """
  Applies a given function to two numbers.

  Args:
    func: The function to apply (should take two arguments).
    x: The first number.
    y: The second number.

  Returns:
    The result of calling func(x, y).
  """
  return func(x, y)

# Demonstrate with addition using a regular function
def add(a, b):
  return a + b

result_add = apply_operation(add, 5, 3)
print(f"Result of addition: {result_add}")

# Demonstrate with subtraction using a lambda function
subtract = lambda a, b: a - b
result_subtract = apply_operation(subtract, 10, 4)
print(f"Result of subtraction: {result_subtract}")

# Demonstrate with multiplication using another lambda function
multiply = lambda a, b: a * b
result_multiply = apply_operation(multiply, 2, 6)
print(f"Result of multiplication: {result_multiply}")Code language: Python (python)

Filed Under: Python, Python Basics, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Loading comments... Please wait.

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2025 pynative.com