Function
Function
1) Creating a Function:
a. def my_function():
print("Hello from a function")
2) Calling a Function:
a. def my_function():
print("Hello from a function")
my_function()
3) Arguments:
a. def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
4) Number of Arguments:
a. def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
5) If you try to call the function with 1 or 3 arguments, you will get an error:
a. def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function definition.
my_function("India")
my_function()
my_function("Brazil")
output: I am from India
I am from Norway
I am from Brazil
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
a) Eg of list as an argument:
a. def my_function(food):
for x in food:
print(x)
my_function(fruits)
output: apple
banana
cherry
print(my_function(3))
print(my_function(5))
print(my_function(9))
output: 15
25
45
To specify that a function can have only positional arguments, add , / after the arguments:
my_function(3)
output: 3
Without the , / you are actually allowed to use keyword arguments even if the function expects
positional arguments:
def my_function(x):
print(x)
my_function(x = 3)
output: 3
eg:
my_function(x = 3)
my_function(x = 3)\
output: 3
Without the *, you are allowed to use positionale arguments even if the function expects
keyword arguments:
my_function(3)
Output: 3
But with the *, you will get an error if you try to send a positional argument:
my_function(3)
Output: Traceback (most recent call last):
File "./prog.py", line 4, in <module>
TypeError: my_function() takes 0 positional arguments but 1 was given
14) Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has
the benefit of meaning that you can loop through data to reach a result.
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Eg: Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
output:
Hello, Jonathan
16) Local Scope
A variable created inside a function belongs to the local scope of that function, and
can only be used inside that function.
def myfunc():
x = 300
print(x)
myfunc()
output:300
Eg: The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
output: 30000
Global variables can be used by everyone, both inside of functions and outside.
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Example: If you use the global keyword, the variable belongs to the
global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python is fantastic
Practice Questions:
Question 1.
def str_exp():
str1= 'COVID-19,Sanitizer,Mask,LockDown'
str1=str1.lower()
str2 =str1.split(',')
for i in str2:
if i<'s':
print(str.lower(i))
else:
print(str.upper(i))
str_exp()
Answer:
covid-19
SANITIZER
mask
lockdown
Question 1(a)
What are the errors in following codes ? Correct the code and predict output :
total = 0;
def sum(arg1, arg2):
total = arg1 + arg2;
print("Total :", total)
return total;
sum(10, 20);
print("Total :", total)
Answer
total = 0
def sum(arg1, arg2):
total = arg1 + arg2
print("Total :", total)
return total
sum(10, 20)
print("Total :", total)
Output
Total : 30
Total : 0
Explanation
Question 1(b)
What are the errors in following codes ? Correct the code and predict output :
Output
6
21
Explanation
1. There should be a colon (:) at the end of the function definition line to indicate the start
of the function block.
2. Python's built-in function for generating sequences is range(), not Range().
3. Python keywords like return should be in lowercase.
4. When calling a function in python, the arguments passed to the function should be
enclosed inside parentheses () not square brackets [].
Question 2
Output
300 @ 200
300 @ 100
120 @ 100
300 @ 120
Explanation
1. Function Call is defined with two parameters P and Q with default values 40 and 20
respectively.
2. Inside the function Call, P is reassigned to the sum of its original value P and the value
of Q.
3. Q is reassigned to the difference between the new value of P and the original value
of Q.
4. Prints the current values of P and Q separated by @.
5. The function returns the final value of P.
6. Two variables R and S are initialized with values 200 and 100 respectively.
7. The function Call is called with arguments R and S, which are 200 and 100
respectively. Inside the function, P becomes 200 + 100 = 300 and Q becomes 300 -
100 = 200. So, 300 and 200 are printed. The function returns 300, which is then
assigned to R. Therefore, R becomes 300.
8. S = Call(S) — The function Call is called with only one argument S, which is 100.
Since the default value of Q is 20, P becomes 100 + 20 = 120, and Q becomes 120 - 20
= 100. So, 120 and 100 are printed. The function returns 120, which is then assigned
to S. Therefore, S becomes 120.
Question 3
Consider the following code and write the flow of execution for this. Line
numbers have been given for your reference.
1. def power(b, p):
2. y = b ** p
3. return y
4.
5. def calcSquare(x):
6. a = power(x, 2)
7. return a
8.
9. n = 5
10. result = calcSquare(n)
11. print(result)
Answer
1 → 5 → 9 → 10 → 5 → 6 → 1 → 2 → 3 → 6 → 7 → 10 → 11
Explanation
Line 1 is executed and determined that it is a function header, so entire function-body (i.e.,
lines 2 and 3) is ignored. Line 5 is executed and determined that it is a function header, so
entire function-body (i.e., lines 6 and 7) is ignored. Lines 9 and 10 are executed, line 10 has
a function call, so control jumps to function header (line 5) and then to first line of function-
body, i.e., line 6, it has a function call , so control jumps to function header (line 1) and then
to first line of function-body, i.e, line 2. Function returns after line 3 to line 6 and then returns
after line 7 to line containing function call statement i.e, line 10 and then to line 11.
Question 4
The function addEm will return None. The provided function addEm takes three parameters x, y,
and z, calculates their sum, and then prints the result. However, it doesn't explicitly return
any value. In python, when a function doesn't have a return statement, it implicitly
returns None. Therefore, the function addEm will return None.
Question 5
Explanation
Question 6(i)
num = 1
def myfunc():
return num
print(num)
print(myfunc())
print(num)
Answer
Output
1
1
1
Explanation
The code initializes a global variable num with 1. myfunc just returns this global variable. Hence,
all the three print statements print 1.
Question 6(ii)
num = 1
def myfunc():
num = 10
return num
print(num)
print(myfunc())
print(num)
Answer
Output
1
10
1
Explanation
1. num = 1 — This line assigns the value 1 to the global variable num.
2. def myfunc() — This line defines a function named myfunc.
3. print(num) — This line prints the value of the global variable num, which is 1.
4. print(myfunc()) — This line calls the myfunc function. Inside myfunc function, num =
10 defines a local variable num and assigns it the value of 10 which is then returned by
the function. It is important to note that the value of global variable num is still 1
as num of myfunc is local to it and different from global variable num.
5. print(num) — This line prints the value of the global variable num, which is still 1.
Question 6(iii)
Output
1
10
10
Explanation
1. num = 1 — This line assigns the value 1 to the global variable num.
2. def myfunc() — This line defines a function named myfunc.
3. print(num) — This line prints the value of the global variable num, which is 1.
4. print(myfunc()) — This line calls the myfunc function. Inside the myfunc function, the
value 10 is assigned to the global variable num. Because of the global keyword used
earlier, this assignment modifies the value of the global variable num to 10. The
function then returns 10.
5. print(num) — This line prints the value of the global variable num again, which is still
1.
Question 6(iv)
def display():
print("Hello", end='')
display()
print("there!")
Answer
Output
Hellothere!
Explanation
The function display prints "Hello" without a newline due to the end='' parameter. When
called, it prints "Hello". Outside the function, "there!" is printed on the same line due to the
absence of a newline.
Question 7
a = 10
y = 5
def myfunc():
y = a
a = 2
print("y =", y, "a =", a)
print("a + y =", a + y)
return a + y
print("y =", y, "a =", a)
print(myfunc())
print("y =", y, "a =", a)
Answer
Explanation
In the provided code, the global variables a and y are initialized to 10 and 5, respectively.
Inside the myfunc function, the line a = 2 suggests that a is a local variable of myfunc. But the
line before it, y = a is trying to assign the value of local variable a to local variable y even
before local variable a is defined. Therefore, this code raises an UnboundLocalError .
Question 8
In the above function definition, the line print("the answer is", x + y + z) is placed after the
return statement. In python, once a return statement is encountered, the function exits
immediately, and any subsequent code in the function is not executed. Therefore, the print
statement will never be executed.
Question 9 Write a function namely fun that takes no parameters and always returns
None.
Answer
def fun():
return
Explanation
def fun():
return
r = fun()
print(r)
The function fun() returns None. When called, its return value is assigned to r,
which holds None. Then print(r) outputs None.
Question 10
Consider the code below and answer the questions that follow :
def multiply(number1, number2):
answer = number1 * number2
print(number1, 'times', number2, '=', answer)
return(answer)
output = multiply(5, 5)
(i) When the code above is executed, what prints out ?
(ii) What is variable output equal to after the code is executed ?
Answer
Question 11
Consider the code below and answer the questions that follow :
def multiply(number1, number2):
answer = number1 * number2
return(answer)
print(number1, 'times', number2, '=', answer)
output = multiply(5, 5)
(i) When the code above is executed, what gets printed ?
Answer
(i) When the code above is executed, it will not print anything because the print statement after the
return statement won't execute. Therefore, the function exits immediately after encountering the
return statement.
(ii) After the code is executed, the variable output is equal to 25. This is because the function multiply
returns the result of multiplying 5 and 5, which is then assigned to the variable output.
Question 12(a)
Question 12(b)
def check():
N = int(input('Enter N:'))
i = 3
answer = 1 + i ** 4 / N
return answer
Question 12(c)
print(alpha("Valentine's Day"):)
print(beta(string = 'true'))
print(alpha(n = 5, "Good-bye"):)
Answer
print(alpha("Valentine's Day"))
print(beta(string='true', n=10))
print(alpha(n=5, string="Good-bye"))
Question 13
Draw the entire environment, including all user-defined variables at the time line 10 is being
executed.
Ans.:
100
20
Ans.:
a=3
b=5
Question1:
Question 2:
Question 3:
Question1: Write a python function named is_underflow() to check a stack is an underflow.
def is_underflow(stk):
if stk==[]:
return True
else:
return False
def push(stk,e):
stk.append(e)
top = len(stk)-1
def pop_stack(stk):
if stk==[]:
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
def display(stk):
if stk==[]:
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
def peek(stk):
if stk==[]:
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
def AddPlayer(player):
pn=input("enter player name:")
player.append(pn)
def DeletePlayer(player):
if player==[]:
print("No player found")
else:
return player.pop()
question 7: Vedika has created a dictionary containing names and marks as key-value pairs of 5
students. Write a program, with separate user-defined functions to perform the following
operations:
1. Push the keys (name of the student) of the dictionary into a stack, where the corresponding value (marks) is
greater than 70.
2. Pop and display the content of the stack.
The dictionary should be as follows:
d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95}
Then the output will be: Umesh Vishal Ishika
def push(stk,item):
stk.append(item)
def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
for i in d:
if d[i]>70:
push(stk,i)
while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break