PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Functions Exercises: 18 Coding Problems with Solutions

Python Functions Exercises: 18 Coding Problems with Solutions

Updated on: June 13, 2026 | 163 Comments

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.
  • Use our Online Code Editor to solve these exercises in real time.
  • Also, Solve Python Exercises: 29 topic-wise exercises with over 800+ coding questions

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

Solution
def demo(name, age):
    # Print the values passed into the function
    print(name, age)

# Call the function with specific arguments
demo("Kelly", 25)Code language: Python (python)

Explanation to Solution:

  • def demo(name, age):: The def keyword tells Python we are defining a function. name and age are placeholders (parameters) that will receive values when the function is called.
  • Function Call: When we run demo("Kelly", 25), the string “Kelly” is assigned to name and 25 is assigned to age.
  • 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
Solution
def func1(*args):
    print("Printing values:")
    for i in args:
        print(i)

# Calling with 3 arguments
func1(20, 40, 60)

# Calling with 2 arguments
func1(80, 100)Code language: Python (python)

Explanation to Solution:

  • *args: The * operator allows the function to receive a tuple containing all positional arguments.
  • The Loop: Since args is a tuple, we use for 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

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

# Get results in a single line
res = calculation(40, 10)
print(res)Code language: Python (python)

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 to add and 30 to sub directly.

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
Solution
def show_employee(name, salary=9000):
    print("Name:", name, "salary:", salary)

# Calling with both arguments
show_employee("Ben", 12000)

# Calling with default value
show_employee("Jessa")Code language: Python (python)

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

Solution
def outer_func(a, b):
    # Inner function
    def addition(a, b):
        return a + b

    # Call inner function and add 5 to the result
    add = addition(a, b)
    return add + 5

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

Explanation to Solution:

  • Scope: The addition() function only exists while outer_func() is running. You cannot call addition() 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

Solution
def addition(num):
    if num:
        # Recursive Case: add current num to the result of addition(num - 1)
        return num + addition(num - 1)
    else:
        # Base Case: stop at 0
        return 0

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

Explanation to Solution:

  • The Base Case (if num: else return 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

Solution
def display_student(name, age):
    print(name, age)

# Assign the function object to a new variable name
show_student = display_student

# Call the function using the new name
show_student("Emma", 26)Code language: Python (python)

Explanation to Solution:

  • Function as Object: show_student = display_student creates 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_student exactly like the original display_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]
Solution
def even_numbers():
    # range(start, stop, step)
    # Use 30 as stop to exclude 30, or 31 to include it if required
    return list(range(4, 30, 2))

print(even_numbers())Code language: Python (python)

Explanation to Solution:

  • range(4, 30, 2): This generates numbers starting at 4, ending before 30, incrementing by 2 every time.
  • list() constructor: A range is a generator object (it doesn’t store all numbers in memory at once). We wrap it in list() 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

Solution
def find_largest(list_input):
    # Assume the first item is the largest
    largest = list_input[0]
    for num in list_input:
        if num > largest:
            largest = num
    return largest

x = [4, 6, 8, 24, 12, 2]
print(find_largest(x))Code language: Python (python)

Explanation to Solution:

  • Initialization: By setting largest = list_input[0], we have a starting point for comparison.
  • Comparison Logic: The if num > largest check acts as a filter. Every time a “new champion” is found, the largest variable 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.
Solution
def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name}.\n")

# Positional arguments: Order matters
describe_pet("hamster", "Harry")

# Keyword arguments: Order does not matter
describe_pet(pet_name="Willie", animal_type="dog")Code language: Python (python)

Explanation to Solution:

  • Positional Call: Python maps “hamster” to animal_type because 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
Solution
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# Calling with three different pieces of named data
print_info(name="Alice", age=30, city="New York")Code language: Python (python)

Explanation to Solution:

  • **kwargs: The double asterisk “packs” the arguments into a dictionary called kwargs.
  • 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
Solution
global_var = 10

def modify_variable():
    global global_var  # Access the variable from the global scope
    global_var = 20

print("Initial:", global_var)
modify_variable()
print("Modified:", global_var)Code language: Python (python)

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

Solution
def recur_factorial(n):
    if n <= 1:
        return 1
    else:
        return n * recur_factorial(n - 1)

num = 5
print(f"The factorial of {num} is {recur_factorial(num)}")Code language: Python (python)

Explanation to Solution:

  • The Chain: When you call recur_factorial(5), it returns 5 * recur_factorial(4), which returns 4 * recur_factorial(3), and so on.
  • The Bottom: Eventually, it hits recur_factorial(1), which returns 1.
  • 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

Solution
# Define the lambda and assign it to a variable
square_num = lambda x: x * x

# Call the lambda just like a regular function
result = square_num(5)
print(result)Code language: Python (python)

Explanation to Solution:

  • lambda x:: This defines the input variable.
  • x * x: This is the operation. Notice there is no name and no def keyword.
  • Anonymity: While we assigned it to square_num here for clarity, lambdas are often used directly inside other functions like map() or filter() 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]

Solution
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# filter(function, iterable)
even_nums = list(filter(lambda x: x % 2 == 0, numbers))

print(even_nums)Code language: Python (python)

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 use list() 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]

Solution
numbers = [1, 2, 3, 4, 5]

# map(function, iterable)
doubled_numbers = list(map(lambda x: x * 2, numbers))

print(doubled_numbers)Code language: Python (python)

Explanation to Solution:

  • lambda x: x * 2: This is the transformation rule. Every x that goes in comes out as x * 2.
  • One-to-One Mapping: Unlike filter, the output of map will 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)]

Solution
students = [("Alice", 88), ("Bob", 75), ("Charlie", 92)]

# Sort using the second element (index 1) of each tuple
sorted_students = sorted(students, key=lambda student: student[1])

print(sorted_students)Code language: Python (python)

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
Solution
def apply_operation(func, x, y):
    return func(x, y)

# Define simple operations
def add(a, b): return a + b
def multiply(a, b): return a * b

# Use the higher-order function
res_add = apply_operation(add, 5, 3)
res_mult = apply_operation(multiply, 5, 3)

print("Addition Result:", res_add)
print("Multiplication Result:", res_mult)Code language: Python (python)

Explanation to Solution:

  • Function Injection: We are “injecting” the add or multiply logic into apply_operation.
  • Abstraction: apply_operation doesn’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.

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有

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

All Coding Exercises:

C Exercises
C++ Exercises
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 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Tesh says

    February 14, 2025 at 12:00 pm

    dont ever call other ppl dumb, cuz thats the dumbest thing to do .><.

    Reply
  2. Abhishek Dubey says

    September 29, 2024 at 9:24 pm

    x = [4, 6, 8, 24, 12, 2]
    def maxs(x):
    x.sort(reverse=True)
    return x[0]
    print(maxs(x))

    as simple

    Reply
    • the guy says

      December 1, 2024 at 4:05 pm

      guys dont be dumb this is the easiest way and simpler

      x = [1,4,7,4,9,8,5]
      max = 0
      for i in x:
      if i > max:
      max = i

      print(max)

      Reply
      • No name says

        March 21, 2025 at 3:55 pm

        well we can also write as
        x = [4, 6, 8, 24, 12, 2]
        n=len(x)
        for i in range(0,n-1):
        if x[i]>x[i+1]:
        x[i],x[i+1]=x[i+1],x[i]
        print(x[-1])

        Reply
  3. aref says

    August 6, 2024 at 11:44 pm

    def larg(number):
    x = number
    x.sort(reverse=True)
    print(x[0])
    NumberList = [2,3,44,5,8,768,5645,3,45,4,435,]
    larg(NumberList)

    Reply
  4. Yassine Ben kacem says

    July 26, 2024 at 2:33 pm

    number= int(input(“The number of elements the list:”))
    for i in range(number):
    print(“X[%d]=” % (i+1),end=””)
    item = int(input())
    X.append(item)
    max = X[0]
    for i in range(1,len(X)):
    if X[0] < X[i]:
    max = X[i]
    print("The given list:",X)
    print("The Max value in this list :",max)

    Reply
    • ron says

      September 18, 2024 at 11:16 am

      over here there is mistake in the second code
      you are using x[0] instead u should have used max
      this way u would have had the result got the maximum

      Reply
  5. Mohmmadsaad Bagwan says

    November 19, 2023 at 11:45 am

    Ex .9 use higher order function :
    from functools import reduce
    x = [4, 6, 8, 24, 12, 2]
    print(reduce(lambda x,y : max(x,y),x))

    Reply
  6. Adrian says

    November 7, 2023 at 11:08 pm

    #9

    def my_function(a):
    x = [4, 6, 8, 24, 12, 2]
    x.sort()
    print (x [a])
    my_function(-1) # max after sort

    Reply
    • Javoxirmirzo says

      October 2, 2025 at 8:09 pm

      x = max([4, 6, 8, 24, 12, 2])
      print(x)

      Reply
  7. DRM says

    October 14, 2023 at 6:15 pm

    Q # 8

    start = 4
    end = 31
    list1 = []
    for i in range(start,end,2):
    list1.append(i)
    print(list1)

    Reply
    • ron says

      September 18, 2024 at 11:18 am

      one way u could have write by using list comprehension
      ;like this
      res = [ i for i in range(s,e,2)]
      print(res)

      Reply
  8. Mira says

    September 2, 2023 at 7:06 pm

    Ex. 9
    x = [4, 6, 8, 24, 1, 2]
    size = len(x)
    max_number = x[0]
    for i in range(1, size):
    if x[i] > max_number:
    max_number = x[i]
    print(max_number)

    Reply
    • RAMANATHAN G says

      September 7, 2023 at 7:39 pm

      Use the power of Python🙂

      Reply
    • Sajid says

      October 6, 2023 at 11:58 am

      x = [4, 6, 8, 24, 12, 2]

      def find_large(x):
      large=x[0]
      for i in range(len(x)):
      if x[i]>large:
      large=x[i]

      return large

      print(find_large(x))

      Reply
      • Irina says

        October 24, 2023 at 11:16 pm

        def largest(list):
        lrg=0
        for i in list:
        if i>lrg:
        lrg=i
        print(lrg)

        x = [4, 6, 8, 24, 12, 2]
        largest(x)

        Reply
  9. shobhit nigam says

    June 19, 2023 at 11:00 pm

    for last question insted of max we can use

    i.sort(reverse=True)
    print(i[0])

    Reply
    • Ismail Abdulazeez says

      September 26, 2023 at 12:50 pm

      Yes, we can also use:

      x.sort()
      print(x[-1])

      Reply
  10. Teshale says

    June 5, 2023 at 12:00 am

    Thanks

    Reply
  11. Dinko says

    June 3, 2023 at 5:58 pm

    Thanks again. Very useful and very well explained. Clear.
    The logic is understandable.

    Reply
  12. Brooks says

    February 21, 2023 at 3:39 am

    Thank you so much Mr Vishal for all, this is so useful!! Everything here is just so well conceived. Clear to understand, and exercises are good way to demonstrate progress, I come a bit late in 2023 but I hope you are still available on line and here.

    Reply
    • essdee says

      March 5, 2026 at 11:29 pm

      3 years later you comment

      Reply
  13. Tani says

    December 28, 2022 at 8:52 pm

    I want to build a function that takes as a parameter a list of integers and an integer n
    the function should return a list of n lists where each list will store the elements that remain after the division with n they have as many positions of the list.
    Example:
    a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12, 13, 14, 15, 16]
    n = 3
    and i want like this:
    [[3, 6, 9, 12, 15], [1, 4, 7, 10, 13, 16,],[2, 5, 8, 11, 14]]

    Reply
    • George says

      January 3, 2023 at 10:19 am

      a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12, 13, 14, 15, 16]

      n = 3
      list_1 = []
      list_2 = []
      list_3 = []

      for i in range(0, len(a), 3):
      list_1.append(i)
      list_2.append(i+1)
      list_3.append(i + 1)

      list_1.pop(0)
      # print(list_1, list_2, list_3)
      res = []

      res.append(list_1)
      res.append(list_2)
      res.append(list_3)

      print(res)

      Reply
      • George says

        January 3, 2023 at 10:27 am

        Sorry made a mistake here.
        Instead of list_3.append(i + 1) it should be list_3.append(i + 2)

        Also, add list_2.pop(-1) to remove the last item in list_3, which is not available in the given list

        Reply
        • Tani says

          January 3, 2023 at 2:05 pm

          thank you so much 🙂

          Reply
    • ShootC says

      February 17, 2023 at 11:59 pm

      I think you are trying to do this with an unlimited amount of n variables, correct?
      In which case I would write this using a dictionary so the amount of keys match whatever your n variable may be.

      # I would do this with a function so you can run it with any variable

      def remain(n):
      # create an empty dict and a list that is the amount of numbers you are trying to iterate through, or your 'a' variable.
      remain_dict = {}
      num_list = [*range(21)]

      # keys will be equal to the range of whatever amount you want to skip by 'n'
      keys = range(0, n)

      # create a loop that adds the value of which you are skipping to the correct key
      for i in keys:
      for x in num_list:
      remain_dict[ i ] = [*range( i, 21, n)]

      #Return just the values
      return remain_dict.values()

      # run the function for whatever your 'n' would be
      print(remain(3))

      Reply
    • pradeep says

      March 29, 2023 at 11:49 am

      def function1(n,List) :
      dlist = []
      list1 = []
      list2 = []
      for i in List :
      if i % n == 0 :
      dlist.append(i)
      elif (i % n == 1) :
      list1.append(i)
      elif (i % n == 2) :
      list2.append(i)
      return dlist, list1, list2

      a, b, c = function1(3,[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
      print(a,b,c)

      Reply
    • nero says

      April 19, 2023 at 4:01 pm

      a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12, 13, 14, 15, 16]
      n=3
      for i in a:
      print(list(range(i,len(a),n)),end=' ')
      if i==a.index(n+1):
      break

      Reply
  14. sunail ahmad says

    December 5, 2022 at 2:48 am

    # Exercise 9: Find the largest item from a given list
    use this code instead of using the max function if you want to build your logics

    def large_finder(n):
    large=n[0]

    for i in n:
    if large<i:
    large=i

    return large

    l=[1,2,3,4,5,55,33,99,5]
    print(f"largest {large_finder(l)}")

    Reply
    • Buterguinho Palma says

      December 28, 2022 at 4:41 pm

      Hi, I appreciate these alternative thank you, but can you explain the logic please. Much thanks

      Reply
      • Suchet says

        September 23, 2023 at 6:49 pm

        This is an alternative way to find the largest number, without using the max() function. The variable is initially assigned the value of the first item in the list n[0]. Then, it uses a for loop to iterate through each item in the list and compare it to the value saved in the variable. If an item value is larger than that stored in the variable, it replaces it. The value returned by the function will be equal to the largest value in the list.

        Reply
    • Aryan Shah says

      December 30, 2022 at 12:18 pm

      Just do this

      x = [4, 6, 8, 24, 12, 2]

      def y():
      z = max(x)

      print(z)

      y()

      Reply
  15. Conor says

    November 21, 2022 at 8:18 am

    Hi, I really like these exercises. 🙂

    In exercise 4, there is a typo. The text in the “Given” box should be “show_employee” rather than “showEmployee” to be consistent with the rest of the example:

    showEmployee("Ben", 12000)
    showEmployee("Jessa")

    In exercise 7 there is a typo in the description show_tudent(name, age) should be show_student(name, age)

    Reply
    • Mohamed Talal says

      October 1, 2023 at 1:57 am

      list=[]
      def show(num):

      for k in num:
      if k %2==0:
      list. append(k)
      return list

      my_range(4,30)
      print(show(my_range))

      Reply
  16. L0NEM4N says

    November 20, 2022 at 9:05 am

    # Exercise 6: Create a recursive function
    # thanks for your effort create this exercise sir

    def recursive(n):
    count = 0
    for i in range(n+1):
    count += i
    print(count)

    recursive(10)

    Reply
    • Vinay kumar says

      November 24, 2022 at 9:56 pm

      Great

      Reply
    • Suchet says

      September 23, 2023 at 6:52 pm

      Your function is not recursive. A recursive function is a function that calls itself, and there is usually no need for a loop within a recursive function.

      Reply
  17. L0NEM4N says

    November 20, 2022 at 8:57 am

    Exercise 5:
    # I think there is another option to become usable the outer assignment square = a ** 2 in the solution

    def outer(a,b):
    a = a + 5
    def inner(a, b):
    return a + b

    res = inner(a,b)
    print(res)

    outer(5,10)

    Reply
  18. KRISHNENDU DUTTA says

    October 25, 2022 at 1:13 pm

    #9) Find the largest item from a given list
    def list_largest (list_num):
    max_num = max(list_num)
    return max_num

    list_num = [5,14,25,2,-1,89]
    highest_num=list_largest(list_num)
    print(f"highest number from the list {list_num} is = {highest_num}")
    print("*"*50)

    Reply
    • KRISHNENDU DUTTA says

      October 25, 2022 at 1:16 pm

      i do not know why spaces are removed from the programmed

      Reply
  19. luke says

    August 2, 2022 at 9:53 pm

    x = [4, 6, 8, 24, 12, 2]
    def max_item(list):
        max = 0
        for y in list:
            if maxy:
                continue
        print(max)
    max_item(x)
    Reply
    • miko says

      August 24, 2022 at 9:31 pm

      x = [5,68,4,27,28]
      
      x.sort()
      print(x[-1])
      Reply
  20. luke says

    August 2, 2022 at 9:39 pm

    solution for exercise 8 other than the one mentioned

    result = list(filter(lambda number: number%2==0, range(4,40+1)))
    print(result)
    Reply
    • VijayKumar says

      January 2, 2023 at 10:39 am

      s = range(6,30,2)
      n = list(filter(lambda x:x%2==0,s))
      print(n)

      Reply
  21. Manik Pant says

    June 14, 2022 at 3:32 pm

    # can someone please help me for understand this code. pleasse leave a answer with proper debugging detaills in each step

    def max_of_two( x, y ):
        if x > y:
            return x
            print(x)
        return y
    def max_of_three( x, y, z ):
        return max_of_two( x, max_of_two( y, z ) )
    print(max_of_three(3, 6, -5))
    Reply
    • Secert Man says

      June 15, 2022 at 11:48 am

      You could never print x.
      ’cause that you’ve already return x, the func is ended.

      Reply
      • syb02 says

        July 20, 2023 at 6:16 am

        +1

        Reply
    • Cynthia Mujyambere says

      July 5, 2022 at 1:30 am

      Let me numerize your codes for better debugging

      #1.def max_of_two( x, y ):
          if x > y:
              return x
              print(x)
          return y
      #2.def max_of_three( x, y, z ):
          return max_of_two( x, max_of_two( y, z ) )
      print(max_of_three(3, 6, -5))
      for line
       #1. you can not return and print x at the same time. You either print or return because of that function declaration. And also, be careful about indentations errors. (return y ) in your code is not indented.
      #2. you can't return a max of two because it is not defined.
      #3. How I can debug this code:
      
      def max_of_two(x,y):
            if x>y:
               return x,y
      def max_of_three(x,y,z):
        if x>y and x>z:
              return x
      elif y>x and y>z:
              return y
      else:
             return z

      Reply
      • syb02 says

        July 20, 2023 at 6:31 am

        1# is wrong, indentation of “return y” is True because that statement is not included in if code block. Manik wants to “return y” when x is not greater than y. It is shortened version of this:

        if x > y:
        return x
        else:
        return y

        2# is also wrong. You can call max_of_two from there because it is already defined above.

        Reply
    • Brooks says

      February 21, 2023 at 1:36 am

      # function that returns de biggest number between two

      def max_of_two( x, y ):
      if x > y:
      return x
      print(x)
      return y

      # function that returns the biggest number between the 3
      def max_of_three( x, y, z ):

      return max_of_two( x, max_of_two( y, z ) ) #returns the first function, with new arguments where the first function is assigned as the 2 last arguments
      print(max_of_three(3, 6, -5))

      Reply
    • shobhit nigam says

      June 19, 2023 at 11:04 pm

      it’s an reccursive function used here, basically calling function inside the function

      Reply
      • syb02 says

        July 20, 2023 at 6:12 am

        No, it’s not recursive, it is just a nested function call. There’s a max_of_two() function call in another max_of_two() function call. Recursive is when there’s a function call in function’s code block and the function that called is that function itself.

        Reply
    • syb02 says

      July 20, 2023 at 5:59 am

      When function returns a value with return statement, lines after that statement do not execute. print(x) must be before “return x” to be execute. Like this:

      def max_of_two( x, y ):
      if x > y:
      print(x)
      return x
      return y
      def max_of_three( x, y, z ):
      return max_of_two( x, max_of_two( y, z ) )
      print(max_of_three(3, 6, -5))

      Reply
      • syb02 says

        July 20, 2023 at 6:01 am

        def max_of_two( x, y ):
        if x > y:
        print(x)
        return x
        return y
        def max_of_three( x, y, z ):
        return max_of_two( x, max_of_two( y, z ) )
        print(max_of_three(3, 6, -5))

        Reply
      • syb02 says

        July 20, 2023 at 6:13 am

        Sorry for indentation errors in code block, i am new in this site.

        Reply
  22. Rishikesh Shah says

    March 15, 2022 at 10:05 am

    To Question 6:

    
    def recursive_fun(x):
        addition = 0
        for i in range(1, x+1):
            addition = addition + i
        
        return addition
    resu = recursive_fun(10)
    print(resu)
    Reply
    • Siddhart Sastri Soojhawon says

      December 29, 2022 at 3:19 am

      Can you please explain me your code. I tried moving the “addition = 0” statement from global to local into the for loop and it gives me back the number that was used as input in the function.

      Example it gives me back 10.

      Reply
    • Suchet says

      September 23, 2023 at 6:58 pm

      This is not a recursive function. A recursive function calls itself.

      Reply
  23. prasad says

    January 17, 2022 at 12:53 pm

    matrix multification using fuction

    Reply
  24. Kanwal says

    January 13, 2022 at 10:28 am

    Question2

    
     def func1(*variable):
        print(variable)
    
    func1('a','b','c')
    Reply
  25. Danilo says

    November 16, 2021 at 1:26 pm

    Question 9

    x = [4, 6, 24, 12, 2]
    z_max = 0
    for num in x:
        if num > z_max:
            z_max = num
    print(z_max)
    Reply
    • Maxwell Oyaro says

      November 24, 2021 at 2:00 pm

      x = [4, 6, 24, 12, 2]
      print(max(x))
      Reply
    • mehdi says

      November 25, 2021 at 6:35 pm

      x = [4,6,24,12,2]
      print(max(x))
      Reply
      • Aryan says

        December 2, 2021 at 11:31 am

        x = [4, 6, 8, 24, 12, 2]
        y=sorted(x)
        print(y[len(y)-1])
        Reply
        • Muskan says

          December 27, 2021 at 1:52 pm

          I need to know what is a way to make programming good. I want to learn

          Reply
        • Maz says

          January 23, 2022 at 4:36 am

          import numpy as np
          x = [4, 6, 8, 24, 12, 2]
          def max_num(x):
               return np.max(x)
          max_num(x)
          Reply
          • Suchet says

            September 23, 2023 at 7:02 pm

            Why would you import numpy when there is a built-in max() function?

    • Anuj Sharma says

      December 9, 2021 at 6:13 pm

      How can we create a function for it?

      Reply
    • Cagri says

      January 29, 2022 at 3:47 am

      dude, all of the items in the list could be negative but your way would print 0
      example:
      x = [ -4, -5.2, -10]
      I also read other comments and most of them are correct but not perfect look at how I did it.

      
      def find_largest_item(list):
          if len(list) == 0:
              print('error: empty list')
          else:
              #y is the first element in the list
              y = list[0]
              for x in list:
                  if x > y:
                      y = x
                  else:
                      continue
              print(y)
      Reply
  26. Danilo says

    November 16, 2021 at 12:03 pm

    Question 5

    def outer_function(a,b):
        def inner_function():
            add = a + b
            return add
        return inner_function() + 5
    
    print(outer_function(2,3)
    Reply
    • SAIKIRAN TANGUDU says

      December 28, 2021 at 6:28 pm

      def func(a,b):
          def same(func):
              return a+b
          return a+b+5
      Reply
      • Suchet says

        September 23, 2023 at 7:09 pm

        Your same() function is not serving any purpose in this code. You could do this:

        def func(a,b):
        def same(c, d):
        return c + d
        return same(a, b) + 5
        print(func(5, 10))

        Reply
        • Suchet says

          September 23, 2023 at 7:13 pm

          def func(a,b):
          def same(c, d):
          return c + d
          return same(a, b) + 5
          print(func(5, 10))

          Reply
          • Suchet says

            September 23, 2023 at 7:27 pm


            def func(a,b):
            def same(c, d):
            return c + d
            return same(a, b) + 5
            print(func(5, 10))

    • Chandu says

      May 10, 2022 at 10:27 pm

      showing error like unexpected EOF while parsing

      Reply
  27. Abigail Gyasi says

    September 22, 2021 at 9:59 am

    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)

    can someone please help me understand: is a recursive function the same as calling an iteration within a function? In this answer, is this the same as iterating within a loop of range(10) and summing up the numbers in this range?

    Reply
    • Isha says

      September 29, 2021 at 5:16 pm

      Apne if else nhi pada h ache s

      Reply
      • Rohith says

        October 4, 2021 at 11:22 am

        Kyun? Sahi tho hain jo unhone likha hain.

        Reply
    • Rohith says

      October 4, 2021 at 11:30 am

      You’re right. Its equivalent of this program. The approach is a bit different and in the recursion approach, you need a base condition to stop the function from reiterating itself.

      sum = 0
      for i in range(11):   
      #using 11 because in range stop value is not included in the range
      sum = sum + i
      
      print(sum)

      Output: 55

      Reply
  28. Jarle Christian says

    September 17, 2021 at 7:46 am

    Exercise 1 with classes so we can make multiple peeps

    class Person:
        def init(self, name,age):
            self.name = name
            self.age = age
    
        def show(self):
            print(f"I am {self.name} and I am {self.age} years old")
    
    class person1(Person):
        def init(self, name,age):
            super().init(name, age)
    
    class person2(Person):
        def init(self, name, age):
            super().init(name, age)
    
    p1 = person1("Jarle", 19)
    på1.show()
    p2 = person2("Marius", 19)
    p2.show()
    Reply
  29. abubakar says

    August 30, 2021 at 4:13 pm

    Exercise 8: Generate a Python list of all the even numbers between 4 to 30

    def even(n):
        evennumber=[]
        for i in range(4,n+1):
            if i%2==0:
                evennumber.append(i)
        print(evennumber)
    even(30)
    Reply
    • Dark side says

      October 6, 2021 at 9:24 pm

      You can put 2 in the range. Like for i in range(4, 30, 2):

      Reply
  30. abubakar says

    August 30, 2021 at 4:11 pm

    #Exercise 9: Return the largest item from the given list

    import numpy as np
    lis=[49,12,55,21,9]
    s=np.sort(lis)
    m=len(s)
    print(s[m-1])
    Reply
  31. Jan says

    August 24, 2021 at 9:56 pm

    Hey there, I love the exercises!

    Quick question regarding no. 9:

    I used the reduce() function since you introduced it to us in this unit.
    Can you please tell me which one is quicker? I assume its Max() because it is built-in and you don’t need to import an additional module, but I couldn’t find an answer online.

    My code:

    from functools import reduce
    l = [4, 6, 8, 24, 12, 2]
    
    print(reduce(lambda x, y: x if x>y else y, l]))

    BTW: I think something like this should be the provided solution because we learned about reduce() in this section. 🙂

    Reply
  32. Narmin says

    August 6, 2021 at 6:27 pm

    #exc 9

    aList = [4, 6, 8, 24, 12, 2]
    maxx=aList[0]
    for i in range(6):
        if maxx<aList[i]:
            maxx=aList[i]
    print("maxx number:",maxx)
    Reply
    • Suchet says

      September 23, 2023 at 7:36 pm

      You can directly iterate through the items in the list with:
      for i in aList:

      Reply
  33. Voided says

    August 5, 2021 at 1:14 am

    Question 4 but with a class instead so we are able to create multiple Employee’s:

    class Employee:
        def __init__(self, name, salary=9000):
            self.name = name
            self.salary = salary
    
    Employee1 = Employee("ben", 69)
    print(Employee1.name, Employee1.salary)

    prints out: “ben 69”, if the salary argument is just left out it prints “ben 9000”

    Reply
  34. Hinata Uzamaki says

    June 26, 2021 at 2:46 pm

    Question – 5

    def outer(a,b):
        def inner(Input):
            sum_1 = a+b
            return sum_1 
        return inner(Input)+5
    
    
    n1 = int(input())
    n2 = int(input())
    ans = outer(n1,n2)
    print(ans)
    Reply
    • Suchet says

      September 23, 2023 at 7:38 pm

      Input is not defined

      Reply
  35. AndyLee says

    June 22, 2021 at 5:52 am

    For number three, I thought we had to remove the parenthesis for the final output, so my solution was:

    def calculate(a,b):
        return a+b,a-b       
    res = calculate(40,10)
    print(*res,sep=',')
    Reply
    • Jan says

      August 24, 2021 at 9:41 pm

      You can also loop through res, that way you don’t need to separate. I assume it makes no difference in speed, so it’s probably a matter of taste.

      Reply
  36. Arpan patidar says

    May 10, 2021 at 10:20 pm

    Good Content .. Very helpful for Beginner

    Reply
  37. Emmanuel Olweny says

    May 7, 2021 at 3:28 pm

    It is pretty good and easy to understand

    Reply
  38. priyanka sargar says

    April 18, 2021 at 4:43 pm

    Write a function addEvenNumber() such that it can accept a variable length of argument,

    and can add all even arguments value and display

    I want to know about this question can somebody will explain me how to do it??

    Reply
    • Pranav Bhagat says

      July 13, 2021 at 12:59 am

      #i want to help 
      #this is the solution ,
      
      def addEvenNumber(*n):
          evens = []
          for j in n:
              if j%2==0:
                  evens.append(j)
      
          a = sum(evens)
                  
          Sum = 0
          for i in evens:
              Sum+=i
          return Sum,a
      
      res1,res2 = addEvenNumber(2,89,76,55,78,4,64,7,71,26)
      print(res1,res2)

      #if you don’t understand contact me on social media(id Pranav Bhagat)
      #i will help you understand the logic

      Reply
    • Sambit S Misra says

      July 13, 2021 at 10:38 pm

      list1 = []
      def addEvenNumber(*args):
          for i in args:
              if i % 2 == 0:
                  list1.append(i)
          return list1, sum(list1)
      
      res1, res2 = addEvenNumber(232,24,255,196,7,77,8,90)
      
      print(res1)
      print(res2)
      Reply
    • dara singh says

      July 19, 2021 at 4:01 pm

      Hello: dear
      in this solve problem:

      List=[i*1 for i in range(2,30) if i%2==0]
      print(List)

      are you happy?

      Reply
    • Suchet says

      September 23, 2023 at 7:52 pm


      def addEvenNumber(*n):
      tot = 0
      for i in n:
      if i % 2 ==0:
      tot += i
      return tot
      print(addEvenNumber(1,2,3,4,5,6,7,8,9,10))

      Reply
  39. Dawar says

    April 5, 2021 at 2:36 pm

    good exercise thanks alot.It help me more. where i get little more complex question?

    Reply
  40. Renegade says

    March 12, 2021 at 7:57 am

    Question 4: A more comprehensive way.

    
    def showEmployee(name, salary):
      default = 9000
      try:
        if salary == "": 
          print("Employee:", name, "Default salary is:", default)
        else:
          print("Employee:", name, "salary is:", int(salary))
      except Exception:
        print("Enter a number for salary")
    
    giveName = input("What's your name? ")
    giveSal = input("What's your salary? ")
    showEmployee(giveName, giveSal)
    Reply
  41. Luis says

    February 4, 2021 at 9:41 pm

    Challenging exercises that sometimes force you to review the Python documentation to solve them.
    I like them very much.

    Reply
  42. ItsRaaz On Youtube says

    February 3, 2021 at 1:02 am

    Good Exercises. Helps me a lot.

    Reply
  43. Div says

    January 17, 2021 at 7:31 pm

    For every solution, if you could explain the rationale behind the solution would be great. Thanks for the great work and helping the community.

    Reply
  44. Rajkumar says

    December 24, 2020 at 1:48 pm

    Question 8

    Type 1:

    for i in range(4,31,2):
        print(i, end=' ')

    Type 2:

    for i in range(4,31):
        if i%2 == 0:
            print(i, end=' ')

    Type 3:

    a = [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]
    for i in a:
        if i%2==0:
            print(i, end=' ')
    Reply
    • Mohan says

      July 31, 2023 at 3:38 pm

      a=[i for i in range(4,32,2)]
      print(a)

      Reply
  45. Rajkumar says

    December 24, 2020 at 1:20 pm

    Question 9

    def find_largest(aList):
        
        return max(aList)
    
    print(find_largest([4, 6, 8, 24, 12, 2]))
    Reply
  46. Rajkumar says

    December 24, 2020 at 11:18 am

    Question 6

    def recursion (num):
        summ = 0
        for i in range(0,num):
            summ += i
            summ += 1
        print(summ)
    recursion(10)
    Reply
    • Suchet says

      September 23, 2023 at 7:58 pm

      This is not recursion

      Reply
  47. Rajkumar says

    December 21, 2020 at 1:17 pm

    Question 3.

    def calculation(a,b):
        return a+b, a-b
    print(calculation(40,10))
    Reply
  48. hemlata mahajan says

    October 31, 2020 at 5:24 pm

    def outer(a,b):
        def inner():
            return a+b
        return(a+b)+5
    
    print(outer(5,6))
    Reply
    • Suchet says

      September 23, 2023 at 7:59 pm

      Your inner function is never called.

      Reply
  49. Abdu says

    October 27, 2020 at 9:06 pm

    question 9

    aList = [28, 6, 8,32, 24, 12, 2]
    largest = aList[0]
    
    for x in aList:
        if x>largest:
            largest = x
    
    print(largest)
    Reply
  50. Abdu says

    October 27, 2020 at 9:02 pm

    question 8 using for loop

    Even_nums = []
    for x in range(4,30):
        if x%2==0:
            Even_nums.append(x)
    print(Even_nums)
    Reply
  51. Abdu says

    October 23, 2020 at 11:43 pm

    question 6 using for loop

    def calculate (index):
        n=0
        for x in range (0,index+1):
            n+=x
        print(n)
    
    calculate(10)
    Reply
  52. Abdu says

    October 23, 2020 at 12:39 am

    question 4

    def showEmployee(name, salary=9000):
    
        return name,salary
    
    print(*showEmployee("Abdu",57887)) #the asterisk will remove the parentheses  and quotation  marks
    Reply
  53. whelan power says

    October 6, 2020 at 2:07 am

    def outerFun(a, b):
        square = a**2
        def innerFun(a,b):
            return a+b
        add = innerFun(a, b)
        return add+5
    
    result = outerFun(5, 10)
    print(result)

    trying to understand in the above code what square = a**2 is doing. when i ran the code without it. i still get 20. also not understanding some parts of what is going on.

    Reply
    • Devashish says

      January 2, 2021 at 7:26 pm

      Hi,
      You are right, square variable is of no use here.

      Which part you didn’t get?

      Reply
    • AndyLee says

      June 22, 2021 at 9:53 am

      I was confused by the same thing. The instructions said nothing about squaring any numbers.

      Reply
      • Nava says

        July 27, 2022 at 3:30 am

        same here

        Reply
  54. ur_bantyness says

    October 3, 2020 at 8:46 pm

    Question no 9: list1 = [4, 6, 8, 24, 12,2]

    max= sorted(list1)
    print(max[-1])
    Reply
  55. mukul says

    September 9, 2020 at 3:42 pm

    can anyone please tell me why there is TypeError coming? thankyou

    
    def func(*args):
        add = 0
        for arg in args:
            if arg > add:
                add=arg
        return add
        
    aList = [4, 6, 8, 24, 12, 2]
    print(func(aList))
    Reply
    • M_from_NL says

      September 20, 2020 at 2:04 pm

      Hi mukul,

      Since you’re working with *args, your for-loop will separate each given argument from the others. In this case you’re working with lists, meaning that using your for-loop with any number of lists as arguments would separate the lists. When given 1 list, a for loop on *args will unpack into an output of 1 list. Your code would execute as follows.

      func([4,2,6],[7,2,1]) # example using 2 lists as arguments
      for arg in args: # separates the arguments (in this case lists)
      arg = [4,2,6] # content of first item
      # if arg > add will become if [4,2,6] > 0, which will result in an error.

      The solution is to add another inner loop to unpack the lists, like this:

      def func(*args):
          add = 0
          for arg in args:
              for item in arg:
                if item> add:
                  add=item
          return add
          
      aList = [4, 6, 8, 24, 12, 2]
      print(func(aList))
      Reply
      • Asali says

        September 12, 2022 at 1:21 am

        Why should we use * before args?
        I am just a beginner

        Reply
        • Suchet says

          September 23, 2023 at 8:04 pm

          This is used when the number of arguments passed to the function may vary, so *args will accept any number of arguments as a tuple, which can then be unpacked.

          Reply
  56. python says

    September 3, 2020 at 3:11 pm

    list = []
    list_1 =[]
    n = int(input("enter the total numbers inside list.:    "))
    i = 1 
    while(i <= n):
        num = int(input("enter the numbers you want to insert into list: "))
        i +=1
        list.append(num)
    print(list, " <--the given list by you is here.\n ")
        
    list.sort()
    print(list)
    print(max(list))
    Reply
  57. Jarin says

    September 1, 2020 at 2:15 pm

    I have some problem on exercise no 6 ..Can anyone help me to explain ?

    Reply
  58. KoussayDhifi says

    August 30, 2020 at 3:09 am

    can someone explain exersise 6 for me

    def calculateSum(num):
        if num:
            return num + calculateSum(num-1)
        else: #why is there else here
            return 0
    
    res = calculateSum(10)
    print(res)

    why is there else there

    Reply
    • M_from_NL says

      September 20, 2020 at 2:21 pm

      Hi Koussay,

      Try looking at it like this:
      The line ‘if num:’ executes the followed statement only if the num-value is still True, when num becomes 0 it would be False and go to the ‘else’-part instead.

      ‘return num + calculateSum(num-1)’ will return the num value to the print function but since the function is called again (with a decrementing num-value) it loops.

      The first round it will look like this:

      
      def calculateSum(num):    # becomes calculateSum(10)
          if num: # becomes if 10: , since 10 corresponds to True, the line below will run.
              return num + calculateSum(num-1)  # return 10 + calculateSum(9) , the second part will run the code again creating a 'loop', each time decrementing the num value by one
          else: # at some point num will become 0, then the if num statement becomes False.
              return 0  # when num becomes 0 there is nothing more to add.

      The code does in effect the same as this one:

      
      def calculateSum(num):
        result = 0
        while num != 0: 
          result = result + num
          num = num - 1
        return result
      
      print(calculateSum(10))
      Reply
  59. Anusha Muthakani says

    July 30, 2020 at 8:55 pm

    Hi Vishal,

    Can you please explain ” Question 9: Return the largest item from the given list ” with some sorting mechanisms instead of using inbuilt fiction?

    Reply
    • Rohit hutagonna says

      August 2, 2020 at 7:13 pm

      alist = [4, 6, 8, 24, 12, 2]
      
      def largest_number(l):
          max_number = l[0]
          for i in range(0, len(l)):
              if max_number < l[i]:
                  max_number = l[i]
          print(max_number)
      
      largest_number(alist) #called the function
      Reply
  60. Shiv Narayan sharma says

    July 30, 2020 at 7:50 pm

    
    #why is this code not return list of even number please reply.
    list=[]
    def l(a,b):
        for i in range(a,b):
            if i%2==0:
                c=list.append(i)
        return c
    v=l(4,30)
    print(v)
    Reply
    • Anusha Muthakani says

      July 30, 2020 at 8:49 pm

      Hi Shiv,

      The empty list should be defined inside a function and no need to assign list values to again new list. Frankly speaking, My first code is also same like as you but i separated both function call and ‘for’ loop. I got the answer, try with below code

      def even():
          l=[]
          for i in range(4,31):
              if i%2 ==0:
                  l.append(i)
          return l
      
      print(even())
      Reply
    • Rohit hutagonna says

      August 2, 2020 at 6:30 pm

      list=[]
      def l(a,b):
          for i in range(a,b):
              if i%2==0:
                  list.append(i)
              c  = list
          return list
      v= l(4,30)
      print(v)

      You must assign the whole list after appending all the numbers
      I think you can’t assign and append for every number simultaneously

      Reply
    • Keyur says

      August 8, 2020 at 5:54 pm

      The thing is when you use append() method on a list it doesn’t return an object, and because it doesn’t return an object you can’t assign a variable to store that object (because it doesn’t exist).

      So when you do, c=list.append(i) it modifies existing list and doesn’t return New list, so your variable c is basically empty.

      You should directly return list, instead of storing it into a variable and returning variable.

      Reply
      • raksha says

        August 16, 2020 at 12:54 am

        thanks

        Reply
    • Bob Butcher says

      September 4, 2020 at 3:07 am

      print(list) insted of print(v) in the last line of code. Also return in the line 6 is not needed.

      Reply
  61. Hassan Turi says

    July 12, 2020 at 2:16 pm

    I have only one suggestion as I am a new programmer so please don’t provide solutions with built-in functions use full code without built-in in solutions

    Reply
  62. Vell says

    July 2, 2020 at 9:51 am

    Good day sir,
    For Q6, this was your answer, can you explain on what is going on with the conditional statements in depth? I have trouble understanding them,Thanks!

    
    def calculateSum(num):
        if num:
            return num + calculateSum(num-1)
        else:
            return 0
    
    res = calculateSum(10)
    print(res)
    Reply
    • Hellboy says

      September 23, 2020 at 6:23 pm

      It is a “recursion” taking place in the above program and in the “if” statement when “num” value becomes zero the condition would not stand true. Here’s how it works
      num = 10
      (this is the result that gets stored to be returned) = 10 + calculatesum(9)

      then the function repeats again
      (result stored) = 10+9+calculatesum(8)
      same step repeats up to 1
      (result stored)= 10+9+8+7+6+5+4+3+2+1+calculatesum(0) –>in this last recursion the function returns “0” thus the sum would become
      10+9+8+7+6+5+4+3+2+1+0 = 55
      and the return function returns the sum.

      Reply
  63. Shahnawaz khan says

    June 2, 2020 at 3:24 pm

    def outerFun(a, b):
        square = a**2        // why this line please tell me
        def innerFun(a,b):
            return a+b
        add = innerFun(a, b)
        return add+5
    
    result = outerFun(5, 10)
    print(result)
    
    Reply
    • Vishal Sharma says

      June 21, 2020 at 11:27 pm

      If u not understand this line u can use pass instead of this linee

      Reply
    • Anukriti says

      July 24, 2020 at 3:17 am

      yeah I have same doubt

      Reply
    • beraat says

      July 27, 2020 at 9:11 pm

      yes, really why?

      Reply
    • Rishikesh Shah says

      March 15, 2022 at 10:03 am

      To Question 5

      
      def outer_fun(a, b):
          def inner_fun():
              return a + b
          res = inner_fun()
          return res +5
      
      result = outer_fun(15, 5)
      print(result)
      Reply
  64. Alec Nigh says

    May 14, 2020 at 10:28 pm

    Hi Vishal! Big fan of your webpages. So I’m having trouble with Q 8… I want to create a class and then solve the problem and this is what I wrote:

    def PythonList(x):
      for x in range(4,30):
        if x % 2 == 0:
          print(x)
        else:
          break
    print(PythonList(x))
    
    can you let me know how you would approach this? Thank you!
    Reply
    • Vishal says

      May 17, 2020 at 8:15 pm

      hey Alec Nigh,

      You should use built-in function if available instead of creating custom logic. Still, if you want to solve it using custom function then you can refer to the following

      numList = []
      
      
      def PythonList(start, end):
          for x in range(start, end):
              if x % 2 == 0:
                  numList.append(x)
          return numList
      
      
      print PythonList(4, 30)
      Reply
      • Alec Nigh says

        July 9, 2020 at 10:14 am

        Thanks Vishal! I see I wasn’t using variables correctly in my original program.

        Reply
      • Dev says

        August 17, 2020 at 11:53 pm

        the shortest solution I got for ques. 8:

        list = []
        
        for i in range(4,30,2):
            list.append(i)
        print(list)
        Reply
    • manuel says

      June 3, 2020 at 12:53 am

      Hi Alec,
      That’s my approach, didn’t like theirs (although, time-wise, much better).

      x = range(4, 30)
      
      for line in x:
          if line % 2 == 0:
              print(line)
      
      Reply
  65. sahil sachdeva says

    May 10, 2020 at 1:06 am

    Hello sir. I just wanted to ask that in question 4 cant we use define function using two arguments and then use if write the function ? can you tell me if this is possible ? if yes how we will write the main code.

    Reply
  66. Aashish says

    May 5, 2020 at 11:44 pm

    Hello sir. Please let me help to understand this I am not able to understand this. the question and the logic as well.

    Exercise Question 2: Write a function func1() such that it can accept a variable length of argument and print all arguments value

    def func1(*args):
        for i in args:
            print(i)
    
    func1(20, 40, 60)
    func1(80, 100)
    
    Reply
    • Vishal says

      May 7, 2020 at 8:33 pm

      Hey, Ashish, we Use *args to get the variable number of positional arguments. if you defined function like def func1(*args) you can now pass n number of postional arguments.

      Reply
  67. Nikhil K says

    April 28, 2020 at 3:12 pm

    Q9:

    aList = [4, 6, 8, 24, 12, 2]
    print(sorted(aList)[-1])
    
    Reply
    • Vamshi says

      May 26, 2020 at 6:55 pm

      aList = [4, 6, 8, 24, 12, 2]
      aList.sort(reverse=True)
      print(aList.pop(0))
      
      Reply
    • Silent fighter says

      July 8, 2021 at 4:46 pm

      It’s mean that first of all that we use sorted () because for this all elements become in ascending order [2,4,6,8,12,24] than and here [-1] mean to show last digit 24…….for example [-2] it showing 2nd last digit which is in list 12

      Reply
  68. Nikhil K says

    April 28, 2020 at 3:01 pm

    Q6:

    def cal(n):
        sum=0
        for i in range(1, n, 1):
            sum = sum +i
        print(sum)
    rev = cal(11)
    
    
    Reply
  69. Anna says

    April 22, 2020 at 12:37 am

    Hello,
    There is a mistake in the description of exercise # 8.
    The range should be between 4 to 30 (not 4 to 40) in order to see the list of even number [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]

    Reply
    • Vishal says

      April 22, 2020 at 10:40 am

      Thank you, Anna, for your observation. I have updated the example you mentioned.

      Reply
      • Dev says

        August 17, 2020 at 11:58 pm

        I did it sir!!!!!Due to your efforts….
        I have no words to complement you!!
        You are doing a great job.

        Reply
        • Vishal says

          August 19, 2020 at 11:42 am

          Thanks for the appreciation dev.

          Reply
          • dara singh says

            July 19, 2021 at 3:48 pm

            for i in range(30):
                 if i%2==0:
                    print("in This 2 to 28",i)
            #another conticen
            method
            num=list(range(4,30,4))
            print(num)
    • Jason says

      February 26, 2024 at 3:10 am

      To get the numbers 4-30 inclusive the solution should be “print(list(range(4, 31, 2)))” (not 30) because the interval of range is open-ended on the right.

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercises for Beginners
  • Loop Exercises
  • Intermediate Python Exercises
  • Input and Output Exercises
  • Functions Exercises
  • String Exercises
  • List Exercises
  • Dictionary Exercises
  • Set Exercises
  • Tuple Exercises
  • Data Structure Exercises
  • Comprehensions Exercises
  • Collections Module Exercises
  • Date and Time Exercises
  • OOP Exercises
  • Exception Handling Exercises
  • Math and Statistics Exercises
  • File Handling Exercises
  • OS and Sys Module Exercises
  • Regex Exercises
  • Lambda & Functional Programming Exercises
  • Iterators & Generators Exercises
  • Itertools & Functools Exercises
  • Random Data Generation Exercises
  • NumPy Exercises
  • Pandas Exercises
  • Matplotlib Exercises
  • Python Database Exercises
  • Python JSON Exercises

 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.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

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

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

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
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有