Python Functions Exercise
Python Functions Exercise
Exercise Question 1: Create a function that can accept two arguments name and
age and print its value
print(name, age)
demo("Ben", 25)
Exercise Question 2: Write a function func1() such that it can accept a variable
length of argument and print all arguments value
func1(80, 100)
Expected Output:
20
40
60
100
def func1(*args):
for i in args:
print(i)
func1(80, 100)
Explanation:
Exercise Question 3: Write a function calculation() such that it can accept two
variables and calculate the addition and subtraction of it. And also it must return
both addition and subtraction in a single return call
For example:
print(res)
Solution:
In Python, we can return multiple values from a function. You can do this by
separating return values with a comma.
print(res)
Or
print(add)
print(sub)
Expected Output:
showEmployee("Ben", 9000)
showEmployee("Ben")
Should Produce:
Solution:
In Python, we can specify default values for arguments when defining a function.
showEmployee("Ben")
Create an inner function inside an outer function that will calculate the addition of
a and b
Solution:
In Python, we can create a nested function inside a function. We can use the
nested function to perform complex tasks multiple times within another function
or avoid loop and code duplication.
square = a**2
def innerFun(a,b):
return a+b
add = innerFun(a, b)
return add+5
result = outerFun(5, 10)
print(result)
Expected Output:
55
def calculateSum(num):
if num:
else:
return 0
res = calculateSum(10)
print(res)
Exercise Question 7: Assign a different name to function and call it through the
new name
print(name, age)
displayStudent("Emma", 26)
showStudent(name, age)
Solution:
print(name, age)
displayStudent("Emma", 26)
showStudent = displayStudent
showStudent("Emma", 26)
Exercise Question 8: Generate a Python list of all the even numbers between 4 to
30
Expected Output:
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
Solution:
Exercise Question 9: Return the largest item from the given list
Expected Output:
24
print(max(aList))