0% found this document useful (0 votes)
1 views

Function

The document provides a comprehensive overview of functions in Python, including their creation, calling, and various types of arguments such as positional, keyword, and arbitrary arguments. It also covers concepts like recursion, local and global variables, and the creation of modules. Additionally, it includes practice questions with explanations and outputs for better understanding.

Uploaded by

vashistv2013
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Function

The document provides a comprehensive overview of functions in Python, including their creation, calling, and various types of arguments such as positional, keyword, and arbitrary arguments. It also covers concepts like recursion, local and global variables, and the creation of modules. Additionally, it includes practice questions with explanations and outputs for better understanding.

Uploaded by

vashistv2013
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

FUNCTION:

A function is a programming block of codes which is


used to perform a single, related task. It only runs
when it is called. We can pass data, known as
parameters, into a function. A function can return data
as a result.
We have already used some python built in functions like print(), etc
and functions defined in module like math.pow(), etc. But we can
also create our own functions. These functions are called user-
defined functions.

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")

6) Arbitrary Arguments, *args :


a. def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


7) Keyword Arguments:

a. def my_function(child3, child2, child1):


print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3
= "Linus")

8) Arbitrary Keyword Arguments, **kwargs:


a. def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

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.

9) Default Parameter Value:


a. def my_function(country = "Norway"):
print("I am from " + country)

my_function("India")
my_function()
my_function("Brazil")
output: I am from India
I am from Norway
I am from Brazil

10) Passing a List as an Argument

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)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

output: apple
banana
cherry

11) Return Values:


a. def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
output: 15
25
45

12) Positional-Only Arguments


You can specify that a function can have ONLY positional arguments, or ONLY keyword arguments.

To specify that a function can have only positional arguments, add , / after the arguments:

def my_function(x, /):


print(x)

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:

def my_function(x, /):


print(x)

my_function(x = 3)

output: Traceback (most recent call last):


File "./prog.py", line 4, in <module>
TypeError: my_function() got some positional-only arguments passed as
keyword arguments: 'x'

13) Keyword-Only Arguments:


a. def my_function(*, x):
print(x)

my_function(x = 3)\
output: 3

Without the *, you are allowed to use positionale arguments even if the function expects
keyword arguments:

Eg: def my_function(x):


print(x)

my_function(3)

Output: 3

But with the *, you will get an error if you try to send a positional argument:

Eg: def my_function(*, x):


print(x)

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.

Eg: def tri_recursion(k):


if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("Recursion Example Results:")


tri_recursion(6)
Output: Recursion Example Results:
1
3
6
10
15
21

15) Create a Module


To create a module just save the code you want in a file with the file extension .py:

Save this code in a file named mymodule.py

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.

A variable created inside a function is available inside that function:

def myfunc():
x = 300
print(x)

myfunc()

output:300

Function Inside Function


As explained in the example above, the variable x is not available outside the function,
but it is available for any function inside the function:

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

17) Global Variables


Variables that are created outside of a function (as in all of the examples in the
previous pages) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

Create a variable outside of a function, and use it inside the function

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

output: Python is awesome


eg: Create a variable inside a function, with the same name as the global
variable
x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)

output: Python is fantastic


Python is awesome

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)

output: Python is fantastic

Example : To change the value of a global variable inside a function,


refer to the variable by using the global keyword:

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

1. There is an indentation error in second line.


2. The return statement should be indented inside function and it should not end with
semicolon.
3. Function call should not end with semicolon.

Question 1(b)

What are the errors in following codes ? Correct the code and predict output :

def Tot(Number) #Method to find Total


Sum = 0
for C in Range (1, Number + 1):
Sum += C
RETURN Sum
print (Tot[3]) #Function Calls
print (Tot[6])
Answer
def Tot(Number): #Method to find Total
Sum = 0
for C in range(1, Number + 1):
Sum += C
return Sum
print(Tot(3)) #Function Calls
print(Tot(6))

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

Find and write the output of the following python code :


def Call(P = 40, Q = 20):
P = P + Q
Q = P - Q
print(P, '@', Q)
return P
R = 200
S = 100
R = Call(R, S)
print(R, '@', S)
S = Call(S)
print(R, '@', S)
Answer

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

The flow of execution for the above program is as follows :

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

What will the following function return ?


def addEm(x, y, z):
print(x + y + z)
Answer

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

What will the following function print when called ?


def addEm(x, y, z):
return x + y + z
print(x + y + z)
Answer

The function addEm prints nothing when called.

Explanation

1. The function addEm(x, y, z) takes three parameters x, y, and z.


2. It returns the sum of x, y, and z.
3. Since the return statement is encountered first, the function exits immediately after
returning the sum. The print statement after the return statement is never executed.
Therefore, it prints nothing.

Question 6(i)

What will be the output of following program ?

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)

What will be the output of following program ?

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)

What will be the output of following program ?


num = 1
def myfunc():
global num
num = 10
return num
print(num)
print(myfunc())
print(num)
Answer

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)

What will be the output of following program ?

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

Predict the output of the following code :

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

The code raises an error when executed.

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

What is wrong with the following function definition ?


def addEm(x, y, z):
return x + y + z
print("the answer is", x + y + z)
Answer

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

(i) When the code above is executed, it prints:


5 times 5 = 25
(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 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 ?

(ii) What is variable output equal to after the code is executed ?

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)

Find the errors in code given below :

def minus(total, decrement)


output = total - decrement
print(output)
return (output)
Answer

The errors in the code are:

def minus(total, decrement) # Error 1


output = total - decrement
print(output)
return (output)

1. There should be a colon at the end of the function definition line.


The corrected code is given below:
def minus(total, decrement):
output = total - decrement
print(output)
return (output)

Question 12(b)

Find the errors in code given below :


define check()
N = input ('Enter N: ')
i = 3
answer = 1 + i ** 4 / N
Return answer
Answer

The errors in the code are:

define check() #Error 1


N = input ('Enter N: ') #Error 2
i = 3
answer = 1 + i ** 4 / N
Return answer #Error 3

1. The function definition lacks a colon at the end.


2. The 'input' function returns a string. To perform arithmetic operations with N, it needs
to be converted to a numeric type, such as an integer or a float.
3. The return statement should be in lowercase.

The corrected code is given below:

def check():
N = int(input('Enter N:'))
i = 3
answer = 1 + i ** 4 / N
return answer

Question 12(c)

Find the errors in code given below :


def alpha (n, string = 'xyz', k = 10) :
return beta(string)
return n

def beta (string)


return string == str(n)

print(alpha("Valentine's Day"):)
print(beta(string = 'true'))
print(alpha(n = 5, "Good-bye"):)
Answer

The errors in the code are:


def alpha (n, string = 'xyz', k = 10) :
return beta(string)
return n #Error 1

def beta (string) #Error 2


return string == str(n)

print(alpha("Valentine's Day"):) #Error 3


print(beta(string = 'true')) #Error 4
print(alpha(n = 5, "Good-bye"):) #Error 5
1. The second return statement in the alpha function (return n) is unreachable because the
first return statement return beta(string) exits the function.
2. The function definition lacks colon at the end. The variable n in the beta function is not
defined. It's an argument to alpha, but it's not passed to beta explicitly. To
access n within beta, we need to either pass it as an argument or define it as a global
variable.
3. There should not be colon at the end in the function call.
4. In the function call beta(string = 'true'), there should be argument for parameter n.
5. In the function call alpha(n = 5, "Good-bye"), the argument "Good-bye" lacks a
keyword. It should be string = "Good-bye".

The corrected code is given below:

def alpha(n, string='xyz', k=10):


return beta(string, n)

def beta(string, n):


return string == str(n)

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.

1. def sum(a, b, c, d):


2. result = 0
3. result = result + a + b + c + d
4. return result
5.
6. def length():
7. return 4
8.
9. def mean(a, b, c, d):
10. return float(sum(a, b, c, d))/length()
11.
12. print(sum(a, b, c, d), length(), mean(a, b, c, d))
Answer
The environment when the line 10 is being executed is shown below :
Eg14: def add(i):
if(i*3%2==0):
i*=i
else:
i*=4
return i
a=add(10)
print(a)
b=add(5)
print(b)

Ans.:
100
20

Eg 15: def fun1(x, y):


x=x+y
y=x–y
x=x–y
print(‘a =’,x)
print(‘b =’,y)
a=5
b=3
fun1(a,b)

Ans.:
a=3
b=5

STACK Based questions:

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

Question2: Write a function to push an element into the stack.

def push(stk,e):
stk.append(e)
top = len(stk)-1

Question3: Write a python function to delete an element from the stack.

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

Question4: Write a function to display the stack elements.

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])

Question 5: Write a function to inspect an element from the stack.

def peek(stk):
if stk==[]:
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]

Question 6: Write functions AddPlayer(player) and DeletePlayer(player) in python to add and


remove a player by considering them as push and pop operations in a stack.

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

You might also like