0% found this document useful (0 votes)
22 views23 pages

Advantage of Functions in Python

Python functions

Uploaded by

logesh ramesh92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views23 pages

Advantage of Functions in Python

Python functions

Uploaded by

logesh ramesh92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

GURU GOBIND SINGH PUBLIC SCHOOL

SECTOR 5/B,B.S.CITY

NOTES AND ASSIGNMENT FOR CLASS XII

SUBJECT: COMPUTER SCIENCE

NOTES

Python Functions
Functions are the most important aspect of an application. A function can be defined
as the organized block of reusable code which can be called whenever required.

Python allows us to divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed by {}. A
function can be called multiple times to provide reusability and modularity to the
python program.

In other words, we can say that the collection of functions creates a program. The
function is also known as procedure or subroutine in other programming languages.

Python provide us various inbuilt functions like range() or print(). Although, the user
can create its functions which can be called user-defined functions.

Advantage of Functions in Python


There are the following advantages of Python functions.

o By using functions, we can avoid rewriting same logic/code again and again in
a program.
o We can call python functions any number of times in a program and from any
place in a program.
o We can track a large python program easily when it is divided into multiple
functions.
o Reusability is the main achievement of python functions.
o However, Function calling is always overhead in a python program.

Creating a function
In python, we can use def keyword to define the function. The syntax to define a
function in python is given below.
1. def my_function():
2. function-suite
3. return <expression>
def my_function():
function-suite
return <expression>

The function block is started with the colon (:) and all the same level block
statements remain at the same indentation.

A function can accept any number of parameters that must be the same in the
definition and function calling.

Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another
function or the python prompt. To call the function, use the function name followed by
the parentheses.

A simple function that prints the message "Hello Word" is given below.

1. def hello_world():
2. print("hello world")
3.
4. hello_world()
def hello_w orld():
print("hello w orld")

hello_w orld()

Output:

hello world

Parameters in function
The information into the functions can be passed as the parameters. The parameters
are specified in the parentheses. We can give any number of parameters, but we
have to separate them with a comma.

Consider the following example which contains a function that accepts a string as the
parameter and prints it.

Example 1
1. #defining the function
2. def func (name):
3. print("Hi ",name);
4.
5. #calling the function
6. func("Ayush")
#defining the function
def func (name):
print("Hi ",name);

#calling the function

Example 2
1. #python function to calculate the sum of two variables
2. #defining the function
3. def sum (a,b):
4. return a+b;
5.
6. #taking values from the user
7. a = int(input("Enter a: "))
8. b = int(input("Enter b: "))
9.
10. #printing the sum of a and b
11. print("Sum = ",sum(a,b))
#python function to calculate th
#defining the function
def sum (a,b):
return a+b;

Output:

Enter a: 10

Enter b: 20

Sum = 30

Call by reference in Python


In python, all the functions are called by reference, i.e., all the changes made to the
reference inside the function revert back to the original value referred by the
reference.

However, there is an exception in the case of mutable objects since the changes
made to the mutable objects like string do not revert to the original string rather, a
new string object is made, and therefore the two different objects are printed.

Example 1 Passing Immutable Object (List)


1. #defining the function
2. def change_list(list1):
3. list1.append(20);
4. list1.append(30);
5. print("list inside function = ",list1)
6.
7. #defining the list
8. list1 = [10,30,40,50]
9.
10. #calling the function
11. change_list(list1);
12. print("list outside function = ",list1);
#defining the function
def change_list(list1):
list1.append(20);
list1.append(30);
print("list inside functi

Output:

list inside function = [10, 30, 40, 50, 20, 30]

list outside function = [10, 30, 40, 50, 20, 30]

Example 2 Passing Mutable Object (String)


1. #defining the function
2. def change_string (str):
3. str = str + " Hows you";
4. print("printing the string inside function :",str);
5.
6. string1 = "Hi I am there"
7.
8. #calling the function
9. change_string(string1)
10.
11. print("printing the string outside function :",string1)
#defining the function
def change_string (str):
str = str + " How s you
print("printing the strin

Output:

printing the string inside function : Hi I am there Hows you

printing the string outside function : Hi I am there

Types of arguments
There may be several types of arguments which can be passed at the time of function
calling.

1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments

Required Arguments
Till now, we have learned about function calling in python. However, we can provide the
arguments at the time of function calling. As far as the required arguments are
concerned, these are the arguments which are required to be passed at the time of
function calling with the exact match of their positions in the function call and function
definition. If either of the arguments is not provided in the function call, or the position
of the arguments is changed, then the python interpreter will show the error.

Consider the following example.

Example 1
1. #the argument name is the required argument to the function func
2. def func(name):
3. message = "Hi "+name;
4. return message;
5. name = input("Enter the name?")
6. print(func(name))

Output:

Enter the name?John


Hi John

Example 2
1. #the function simple_interest accepts three arguments and returns the simple interest a
ccordingly
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. p = float(input("Enter the principle amount? "))
5. r = float(input("Enter the rate of interest? "))
6. t = float(input("Enter the time in years? "))
7. print("Simple Interest: ",simple_interest(p,r,t))

Output:

Enter the principle amount? 10000


Enter the rate of interest? 5
Enter the time in years? 2
Simple Interest: 1000.0

Example 3
1. #the function calculate returns the sum of two arguments a and b
2. def calculate(a,b):
3. return a+b
4. calculate(10) # this causes an error as we are missing a required arguments b.

Output:

TypeError: calculate() missing 1 required positional argument: 'b'

Keyword arguments
Python allows us to call the function with the keyword arguments. This kind of function
call will enable us to pass the arguments in the random order.

The name of the arguments is treated as the keywords and matched in the function
calling and definition. If the same match is found, the values of the arguments are
copied in the function definition.

Consider the following example.

Example 1
1. #function func is called with the name and message as the keyword arguments
2. def func(name,message):
3. print("printing the message with",name,"and ",message)
4. func(name = "John",message="hello") #name and message is copied with the values Jo
hn and hello respectively

Output:

printing the message with John and hello

Example 2 providing the values in different order at the calling


1. #The function simple_interest(p, t, r) is called with the keyword arguments the order of
arguments doesn't matter in this case
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))

Output:
Simple Interest: 1900.0

If we provide the different name of arguments at the time of function call, an error will
be thrown.

Consider the following example.

Example 3
1. #The function simple_interest(p, t, r) is called with the keyword arguments.
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4.
5. print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900)) # doesn
't find the exact match of the name of the arguments (keywords)
#The function simple_interest(p
def simple_interest(p,t,r):
return (p*t*r)/100

print("Simple Interest: ",simple_in

Output:

TypeError: simple_interest() got an unexpected keyword argument 'time'

The python allows us to provide the mix of the required arguments and keyword
arguments at the time of function call. However, the required argument must not be
given after the keyword argument, i.e., once the keyword argument is encountered in
the function call, the following arguments must also be the keyword arguments.

Consider the following example.

Example 4
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello",name2="David") #the first argument is not the keywor
d argument
def func(name1,message,name
print("printing the message w
func("John",message="hello",na

Output:

printing the message with John , hello ,and David


The following example will cause an error due to an in-proper mix of keyword and
required arguments being passed in the function call.

Example 5
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello","David")
def func(name1,message,name
print("printing the message w
func("John",message="hello","D

Output:

SyntaxError: positional argument follows keyword argument

Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of
any of the argument is not provided at the time of function call, then that argument
can be initialized with the value given in the definition even if the argument is not
specified at the function call.

Example 1
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however th
e default value of age is considered in the function
def printme(name,age=22):
print("My name is",name,"and
printme(name = "john") #the var

Output:

My name is john and age is 22

Example 2
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however th
e default value of age is considered in the function
4. printme(age = 10,name="David") #the value of age is overwritten here, 10 will be pr
inted as age
def printme(name,age=22):
print("My name is",name,"and
printme(name = "john") #the var
printme(age = 10,name="David"

Output:

My name is john and age is 22

My name is David and age is 10

Variable length Arguments


In the large projects, sometimes we may not know the number of arguments to be
passed in advance. In such cases, Python provides us the flexibility to provide the
comma separated values which are internally treated as tuples at the function call.

However, at the function definition, we have to define the variable with * (star) as
*<variable - name >.

Consider the following example.

Example
1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
5. print(name)
6. printme("john","David","smith","nick")
def printme(*names):
print("type of passed argume
print("printing the passed arg
for name in names:
print(name)

Output:

type of passed argument is <class 'tuple'>

printing the passed arguments...

john

David

smith

nick

Scope of variables
The scopes of the variables depend upon the location where the variable is being
declared. The variable declared in one part of the program may not be accessible to
the other parts.

In python, the variables are defined with the two types of scopes.

1. Global variables
2. Local variables

The variable defined outside any function is known to have a global scope whereas
the variable defined inside a function is known to have a local scope.

Consider the following example.

Example 1
1. def print_message():
2. message = "hello !! I am going to print a message." # the variable message is loc
al to the function itself
3. print(message)
4. print_message()
5. print(message) # this will cause an error since a local variable cannot be accessible
here.
def print_message():
message = "hello !! I am going
print(message)
print_message()
print(message) # this w ill cause

Output:

hello !! I am going to print a message.

File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in

print(message)

NameError: name 'message' is not defined

Example 2
1. def calculate(*args):
2. sum=0
3. for arg in args:
4. sum = sum +arg
5. print("The sum is",sum)
6. sum=0
7. calculate(10,20,30) #60 will be printed as the sum
8. print("Value of sum outside the function:",sum) # 0 will be printed
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)

Output:

The sum is 60
Value of sum outside the function: 0

ASSIGNMENT

TOPIC-1
Python Basics
Very Short Answer Type Questions(1 mark)

Question 1.
Name the Python Library modules which need to be imported to invoke the following
functions :

1. load ()
2. pow () [CBSE Delhi 2016]

Question 2.
Name the modules to which the following func-tions belong:

1. Uniform ()
2. fabs ()

Question 3.
Differentiate between the round() and floor() functions with the help of suitable example.

Short Answer Type Questions (2 marks):

Question 1.
Out of the following, find those identifiers, which cannot be used for naming Variables or
functions in a Python program:
Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total.

Question 2.
Name the Python Library modules which need to be imported to invoke the follwing
functions :

1. sqrt()
2. dump()
Question 3.
Out of the following, find the identifiers, which cannot be used for naming Variable or
Functions in a Python program: [CBSE Delhi 2016]
_Cost, Price*Qty, float, switch, Address one, Delete, Number12, do

Question 4.
Out of the following find those identifiers, which can not be used for naming Variable or
Functions in a Python Program:
Days * Rent, For, A_price, Grand Total, do, 2Clients, Participantl, My city

Question 5.
Name the function / method required for

1. Finding second occurrence of m in madam.


2. get the position of an item in the list.

Question 6.
Which string method is used to implement the following:

1. To count the number of characters in the string.


2. To change the first character of the string in capital letter.
3. To check whether given character is letter or a number.
4. To change lowercase to uppercase letter.
5. Change one character into another character.

Question 7.
What is the difference between input() and raw_input()?

Question 8.
What are the two ways of output using print()?.

Question 9.
Why does the expression 2 + 3*4 result in the value 14 and not the value 24?

Question 10.
How many times will Python execute the code inside the following while loop? You should
answer the question without using the interpreter! Justify your answers.

i = 0
while i < 0 and i > 2 :
print “Hello ...”
i = i+1
.

Question 11.
How many times will Python execute the code inside the following while loop?
i = 1
while i < 10000 and i > 0 and 1:
print “ Hello ...”
i = 2 * i

Question 12.
Convert the following for loop into while loop, for i in range (1,100):

if i % 4 == 2 :
print i, “mod”, 4 , “= 2”

Question 13.
Convert the following for loop into while loop.

for i in range(10):
for j in range(i):
print '$',
print"

Question 14.
Rewrite the following for loop into while loop:

for a in range(25,500,25):
print a

Question 15.
Rewrite the following for loop into while loop:

for a in range(90, 9, -9):


print a

Question 16.
Convert the following while loop into for loop:

i = 0
while i < 100:
if i % 2 == 0:
print i, “is even”
else:
print i, “is odd”
i = i + 1

Question 17.
Convert the following while loop into for loop
char = ""
print “Press Tab Enter to stop ...”
iteration = 0
while not char == “\t” and not iteration > 99:
print “Continue?”
char = raw_input()
iteration+ = 1

Question 18.
Rewrite the following while loop into for loop:

i = 10
while i<250:
print i
i = i+50

Question 19.
Rewrite the following while loop into for loop:

i=88
while(i>=8): print i
i- = 8

Question 20.
Write for statement to print the series 10,20,30, ……., 300

Question 21.
Write for statement to print the series 105,98,91,… .7

Question 22.
Write the while loop to print the series: 5,10,15,…100

Question 23.
How many times is the following loop executed?
for a in range(100,10,-10):
print a.

Question 24.
How many times is the following loop executed?

i = 100
while (i<=200):
print i
i + =20
Question 25.
State whether the statement is True or False? No matter the underlying data type if values are
equal returns true,

char ch1, ch2;


if (ch1==ch2)
print “Equal”

Question 26.
What are the logical operators of Python?

Question 27.
What is the difference between „/‟ and „//‟ ?

Question 28.
How can we import a module in Python?

Question 29.
What is the difference between parameters and arguments?
Question 30.
What are default arguments?

Question 31.
What are keyword arguments?

Question 32.
What are the advantages of keyword arguments?

Question 33.
What does “in” do?

Question 34.
What does “not in” do?

Question 35.
What does “slice” do?

Question 36.
What is the use of negative indices in slicing?
Question 37.
Explain find() function?

Question 38.
What are the differences between arrays and lists?.

Question 39.
What is the difference between a tuple and a list?

Question 40.
Carefully observe the following python code and answer the question that follows:
x=5
def func2():
x=3
global x
x=x+1
print x
print x
On execution the above code produces the following output.
6
3
Explain the output with respect to the scope of the variables.

Question 41.
Explain the two strategies employed by Python for memory allocation.

TOPIC – 2

Writing Python Programs

Question 1.
Rewrite the following code in Python after removing all syntax errors(s). Underline each
correction done in the code.
for Name in [Amar, Shveta, Parag]
if Name [0] = „s‟:
Print (Name)

Question 2.
Rewrite the following code is Python after removing all syntax errors(s).
Underline each correction done in the code.
for Name in [Ramesh, Suraj, Priya]
if Name [0] = „S‟:
Print (Name)
Question 3.
What will be the output of the following python code considering the following set of inputs?
AMAR
THREE
A123
1200
Also, explain the try and except used in the code.
Start = 0
while True :
Try:
Number = int (raw input (“Enter Number”))
break
except valueError : start=start+2
print (“Re-enter an integer”)
Print (start)

Question 4.
Give the output of following with justification.

x = 3
x+ = x-x
print x

Question 5.
What would be the output of the following code snippets?
print 4+9
print “4+9”

Question 6.
Highlight the literals in the following program
and also predict the output. Mention the types of
variables in the program.

a=3
b='1'
c=a-2
d=a-c
e=“Kathy”
f=„went to party.‟
g=„with Sathy‟
print a,g,e,f,a,g,“,”,d,g,“,”,c,g,“and his”,e,f

Question 7.
What is the result of 4+4/2+2?
Question 8.
Write the output from the following code:

x= 10
y = 20
if (x>y):
print x+y
else:
print x-y

Question 9.
Write the output of the following code:
print “Python is an \n interpreted \t Language”

Question 10.
Write the output from the following code:

s = 0
for I in range(10,2,-2):
s+=I
print “sum= ",s

Question 11.
Write the output from the following code:

n = 50
i = 5
s = 0
while i<n:
s+ = i
i+ = 10
print “i=”,i
print “sum=”,s
i= 55
sum= 125

Question 12.
Write the output from the following code:

n = 50
i = 5
s = 0
while i<n:
s+ = i
i+ = 10
print “i=”,i
print “sum=”,s
Question 13.
Observe the following Python code carefully and obtain the output, which will appear on the
screen after execution of it. [CBSE SQP 2016]

def Findoutput ():


L = "earn"
X = " "
count = 1
for i in L:
if i in ['a', 'e',' i', 'o', 'u']:
x = x + 1. Swapcase ()
else:
if (count % 2 ! = 0):
x = x + str (len (L[:count]))
else:
x = x + 1
count = count + 1
print x
Findoutput ()

Question 14.
Find and write the output of the following Python code:

Number = [9,18,27,36] for N in Numbers:


print (N, "#", end = " ")
print ()

Question 15.
Find and write the output of the following Python code :

Values = [10,20,30,40]
for val in Values:
for I in range (1, Val%9):
print (I," * ", end= " ")
print ()

Question 16.
Write the output from the following code:

y = 2000
if (y%4==0):
print “Leap Year”
else:
print “Not leap year”
Question 17.
What does the following print?

for i in range (1,10):


for j in'range (1,10):
print i * j,
print

Question 18.
What will be the output of the following statement? Also, justify the answer.

>> print „Radhsa‟s dress is pretty‟.

Question 19.
Give the output of the following statements :

>>> str=„Honesty is the best policy‟


>>> str.replace(„o‟,„*‟)

Question 20.
Give the output of the following statements :

>> str=„Hello Python‟


>>> str.istitle()

Question 21.
Give the output of the following statements:

>> str=„Hello Python‟


>>> print str.lstrip(“Hel”)

Question 22.
Write the output for the following codes:

A={10:1000,20:2000,30:3000,40:4000,50:5000}
print A.items()
print A.keys()
print A.values()

Question 23.
Write the output from the following code:

t=(10,20,30,40,50)
print len(t)
Question 24.
Write the output from the following code:

t=(„a‟,„b‟,„c‟,„A‟,„B‟)
print max(t)
print min(t)

Question 25.
Find the output from the following code:

T=(10,30,2,50,5,6,100,65)
print max(T)
print min(T)

Question 26.
Write the output from the following code:

T1=(10,20,30,40,50)
T2 =(10,20,30,40,50)
T3 =(100,200,300)
cmp(T1, T2)
cmp(T2,T3)
cmp(T3,T1)

Question 27.
Write the output from the following code:

T1=(10,20,30,40,50)
T2=(100,200,300)
T3=T1+T2
print T3

Question 28.
Find the output from the following code:

t=tuple()
t = t +(„Python‟,)
print t
print len(t)
t1=(10,20,30)
print len(t1)
Question 29.
Rewrite the following code in Python after remo¬ving all syntax error(s).
Underline each correction done in the code.

for student in [Jaya, Priya, Gagan]


If Student [0] = „S‟:
print (student)

Question 30.
Find and write the output of the following Python code:

Values = [11, 22, 33, 44] for V in Values:


for NV in range (1, V%10):
print (NV, V)

Question 31. Write a Python function to find the Max of three numbers.

Question 32. Write a Python function to sum all the numbers in a list.

Sample List : (8, 2, 3, 0, 7)


Expected Output : 20

Question 33. Write a Python function to multiply all the numbers in a list. Sample List
: (8, 2, 3, -1, 7)
Expected Output : -336

Question 34. Write a Python program to reverse a string.


Sample String : "1234abcd"
Expected Output : "dcba4321"

Question 35. Write a Python function to calculate the factorial of a number (a non-
negative integer). The function accepts the number as an argument.

Question 36. Write a Python function to check whether a number is in a given range.

Question 37. Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.
Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12

Question 38. Write a Python function that takes a list and returns a new list with
unique elements of the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]

Question 39. Write a Python function that takes a number as a parameter and check the
number is prime or not.

Note : A prime number (or a prime) is a natural number greater than 1 and that has no
positive divisors other than 1 and itself.

Question 40. Write a Python program to print the even numbers from a given list.
Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result : [2, 4, 6, 8]

You might also like