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

dont ever call other ppl dumb, cuz thats the dumbest thing to do .><.
x = [4, 6, 8, 24, 12, 2]
def maxs(x):
x.sort(reverse=True)
return x[0]
print(maxs(x))
as simple
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)
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])
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)
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)
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
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))
#9
def my_function(a):
x = [4, 6, 8, 24, 12, 2]
x.sort()
print (x [a])
my_function(-1) # max after sort
x = max([4, 6, 8, 24, 12, 2])
print(x)
Q # 8
start = 4
end = 31
list1 = []
for i in range(start,end,2):
list1.append(i)
print(list1)
one way u could have write by using list comprehension
;like this
res = [ i for i in range(s,e,2)]
print(res)
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)
Use the power of Python🙂
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))
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)
for last question insted of max we can use
i.sort(reverse=True)print(i[0])
Yes, we can also use:
x.sort()
print(x[-1])
Thanks
Thanks again. Very useful and very well explained. Clear.
The logic is understandable.
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.
3 years later you comment
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]]
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)Sorry made a mistake here.
Instead of
list_3.append(i + 1)it should belist_3.append(i + 2)Also, add
list_2.pop(-1)to remove the last item inlist_3, which is not available in the given listthank you so much 🙂
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 beprint(remain(3))
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)
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
# Exercise 9: Find the largest item from a given listuse 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)}")
Hi, I appreciate these alternative thank you, but can you explain the logic please. Much thanks
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.
Just do this
x = [4, 6, 8, 24, 12, 2]def y():
z = max(x)
print(z)
y()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 beshow_student(name, age)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))
# 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)Great
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.
Exercise 5:
# I think there is another option to become usable the outer assignment
square = a ** 2in the solutiondef outer(a,b):a = a + 5
def inner(a, b):
return a + b
res = inner(a,b)
print(res)
outer(5,10)#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)
i do not know why spaces are removed from the programmed
solution for exercise 8 other than the one mentioned
s = range(6,30,2)n = list(filter(lambda x:x%2==0,s))
print(n)
# can someone please help me for understand this code. pleasse leave a answer with proper debugging detaills in each step
You could never print x.
’cause that you’ve already return x, the func is ended.
+1
Let me numerize your codes for better debugging
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.
# function that returns de biggest number between twodef 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 argumentsprint(max_of_three(3, 6, -5))
it’s an reccursive function used here, basically calling function inside the function
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.
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))
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))
Sorry for indentation errors in code block, i am new in this site.
To Question 6:
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.
This is not a recursive function. A recursive function calls itself.
matrix multification using fuction
Question2
Question 9
I need to know what is a way to make programming good. I want to learn
Why would you import numpy when there is a built-in max() function?
How can we create a function for it?
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.
Question 5
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))
def func(a,b):
def same(c, d):
return c + d
return same(a, b) + 5
print(func(5, 10))
def func(a,b):
def same(c, d):
return c + d
return same(a, b) + 5
print(func(5, 10))
showing error like unexpected EOF while parsing
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?Apne if else nhi pada h ache s
Kyun? Sahi tho hain jo unhone likha hain.
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.
Output: 55
Exercise 1 with classes so we can make multiple peeps
Exercise 8: Generate a Python list of all the even numbers between 4 to 30
You can put 2 in the range. Like
for i in range(4, 30, 2):#Exercise 9: Return the largest item from the given list
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:
BTW: I think something like this should be the provided solution because we learned about reduce() in this section. 🙂
#exc 9
You can directly iterate through the items in the list with:
for i in aList:
Question 4 but with a class instead so we are able to create multiple Employee’s:
prints out: “ben 69”, if the salary argument is just left out it prints “ben 9000”
Question – 5
Input is not defined
For number three, I thought we had to remove the parenthesis for the final output, so my solution was:
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.
Good Content .. Very helpful for Beginner
It is pretty good and easy to understand
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??
#if you don’t understand contact me on social media(id Pranav Bhagat)
#i will help you understand the logic
Hello: dear
in this solve problem:
are you happy?
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))
good exercise thanks alot.It help me more. where i get little more complex question?
Question 4: A more comprehensive way.
Challenging exercises that sometimes force you to review the Python documentation to solve them.
I like them very much.
Good Exercises. Helps me a lot.
For every solution, if you could explain the rationale behind the solution would be great. Thanks for the great work and helping the community.
Question 8
Type 1:
Type 2:
Type 3:
a=[i for i in range(4,32,2)]
print(a)
Question 9
Question 6
This is not recursion
Question 3.
Your inner function is never called.
question 9
question 8 using for loop
question 6 using for loop
question 4
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.
Hi,
You are right, square variable is of no use here.
Which part you didn’t get?
I was confused by the same thing. The instructions said nothing about squaring any numbers.
same here
Question no 9:
list1 = [4, 6, 8, 24, 12,2]can anyone please tell me why there is TypeError coming? thankyou
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:
Why should we use
*before args?I am just a beginner
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.
I have some problem on exercise no 6 ..Can anyone help me to explain ?
can someone explain exersise 6 for me
why is there else there
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:
The code does in effect the same as this one:
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?
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
You must assign the whole list after appending all the numbers
I think you can’t assign and append for every number simultaneously
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.
thanks
print(list) insted of print(v) in the last line of code. Also return in the line 6 is not needed.
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
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!
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 become10+9+8+7+6+5+4+3+2+1+0 = 55
and the return function returns the sum.
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)If u not understand this line u can use pass instead of this linee
yeah I have same doubt
yes, really why?
To Question 5
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))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)Thanks Vishal! I see I wasn’t using variables correctly in my original program.
the shortest solution I got for ques. 8:
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)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.
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)Hey, Ashish, we Use
*argsto get the variable number of positional arguments. if you defined function likedef func1(*args)you can now pass n number of postional arguments.Q9:
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 12Q6:
def cal(n): sum=0 for i in range(1, n, 1): sum = sum +i print(sum) rev = cal(11)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]
Thank you, Anna, for your observation. I have updated the example you mentioned.
I did it sir!!!!!Due to your efforts….
I have no words to complement you!!
You are doing a great job.
Thanks for the appreciation dev.
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.