You are on page 1of 9

12 CS Guide R.M.K.MATRIC.HR.SEC.

SCHOOL - 601206

Namma Kalvi
UNIT CHAPTER 7 PYTHON FUNCTION
II ALGORITHMIC STRATEGIES
www.nammakalvi.in

1.Define function and its advantages. User Defined functions


What are the advantages of user defined functions Define User defined function
 Functions are named blocks of code that are Functions defined by the users themselves.
designed to do specific job Syntax:
Advantage : def function_name (parameter1, parameter2… ) :
Block of Statements
 Functions help us to divide a program into modules
return (expression / None)
 It avoids repetition
 Function code can be reuse .  Function begin with def keyword followed by
 It provides better modularity for application. function name and parenthesis ().
2.What are the types of function in python  parameters or arguments should be placed within
parenthesis ().
Functions Description  The code block is indented and always comes after
User-defined Functions defined by the a colon (:).
functions users themselves.  The statement “return [expression]” exits a
Functions that are inbuilt function,
Built-in functions
with in Python  A “return” with no arguments is the same as return
Functions that are None.
Anonymous or
anonymous un-named Example:
Lambda functions
function def hello():
Functions that calls itself is print(“Hello”)
Recursion functions
known as recursive return
hello()
Advantage :
3.What is meant by block in python?  Functions help us to divide a program into modules
How statements in a blank are written in python.  It avoids repetition
 A block is one or more lines of code, grouped  It implements code reuse .
together and treated as one big sequence of  It provides better modularity for application.
statements during execution. Anonymous or lambda function
 In Python, statements in a block are written with Define Anonymous or lambda function
indentation (by four spaces).  It is defined without a name.
4.Explain the different types of function in python  Instead of def keyword lambda keyword is used.
with an example.  also called as lambda functions.
There are four types of functions in python, they are  Lambda function can take any number of
 User Defined functions arguments
 Anonymous or Lambda functions  Must return one value in the form of an expression.
 Recursion functions  Lambda function can only access global variables
 Built-in functions and variables in its parameter list
Syntax: lambda arg1,arg2,arg3…argn : expression
Example:
s=lambda a,b,c : a+b+c
print(s(10,20,30))
>>>60

Elangovan 9677515019 Page 1


12 CS Guide R.M.K.MATRIC.HR.SEC.SCHOOL - 601206

Advantage 7.How to set the limit for recursive function? Give an


 Lambda function is mostly used for creating small example
and one-time anonymous function.  python stops calling recursive function after 1000
 Lambda functions are mainly used in combination calls by default.
with the functions like filter(), map() and reduce().  It also allows you to change the limit using
Recursive functions sys.setrecursionlimit (limit_value)
Define recursive function or How recursive function Example:
works? Or . Explain recursive function with an example import sys
 A recursive function calls itself. sys.setrecursionlimit(3000)
 Recursion works like loop def fact(n):
 The condition that is applied in any recursive if n == 0:
function is known as base condition. return 1
 A base condition is must in every recursive function else:
otherwise it will execute like an infinite loop return n * fact(n-1)
Example: print(fact (2000))
import sys 8.What is base condition in recursive function?
sys.setrecursionlimit(3000)  The condition that is applied in any recursive
def fact(n): function is known as base condition.
if n == 0:  A base condition is must in every recursive function
return 1 otherwise it will execute like an infinite loop
else:
return n * fact(n-1) 9.How to define functions in python
print(fact (2000)) What are the points to be noted while defining a
base condition function?
 The condition that is applied in any recursive  Function begin with def keyword followed by
function is known as base condition. function name and parenthesis ().
 A base condition is must in every recursive function  parameters or arguments should be placed within
otherwise it will execute like an infinite loop parenthesis ().
Built-in functions  The code block is indented and always comes after
 Functions that are inbuilt with in Python a colon (:).
 Ex. abs(),ord(),chr(),bin(),max(),min(),sum() etc…  The statement “return [expression]” exits a
function,
5.Differentiate between anonymous function and  A “return” with no arguments is the same as return
normal functions None.
Anonymous function Normal function Syntax:
Defined without a Defined with a name. def function_name (parameter1, parameter2… ) :
Block of Statements
name.
return (expression / None)
defined using the defined using the def
lambda keyword. keyword 10.How to call a function?
 Call function used to call the function
6.What is the use of lambda or anonymous function? Syntax:
 Lambda function is mostly used for creating small Function_name(argument)
and one-time anonymous function.
 Lambda functions are mainly used in combination 11.Define parameters and arguments
with the functions like filter(), map() and reduce().  Parameters are the variables used in the function
definition.
 Arguments are the values we pass to the function
parameters

Elangovan 9677515019 Page 2


12 CS Guide R.M.K.MATRIC.HR.SEC.SCHOOL - 601206

12.Explain the different types of arguments with an 4.Variable-Length Arguments


example.  It is used pass more arguments than have already
 Arguments are used to call a function. been specified.
There are primarily 4 types of Arguments, They are  Arguments are not specified in the function’s
1. Required arguments, definition
2. Keyword arguments,  An asterisk (*) is used to define such arguments.
3. Default arguments and
4. Variable-length arguments. Syntax:
def function_name(*args):
1.Required arguments function_body
 “Required Arguments” are the arguments passed to return_statement
a function in correct positional order. Example:
 Here, the number of arguments in the function call def add(*x):
should match exactly with the function definition. for a in x:
Ex. print(a)
def add(x,y): add(2,3)
add(2,3,4)
print(x+y)
output:
add(5,6) 2
Out put : 11 3
2.Keyword Arguments 2
 Keyword arguments will invoke by their parameter 3
names. 4
 The value is matched with the parameter name >>>
arguments can be in any order. Two methods of pass Variable-Length Arguments
def printdata (n, a): 1. Non keyword variable arguments
print ("Name :",n) 2. Keyword variable arguments
print ("Age :",a) Name the methods of passing Variable-Length
printdata (a=25, n=”elango") Arguments
output: Name : elango Two methods of pass Variable-Length Arguments
Age : 25 1. Non keyword variable arguments
3.Default Arguments 2. Keyword variable arguments
 In Python the default argument is an argument that
takes a default value if no value is provided in the 14.Write a short note on return Statement
calling function.  It is used to exit from function and returns a value
Example: to calling statement
def sal( n, s = 3500):  Any number of 'return' statements are allowed in a
print (“Name: “, n) function definition but only one of them is executed
print (“Salary: “, s) at run time
sal(“Elango”)  This statement can contain expression which gets
output: evaluated and the value is returned.
Name:Elango  If there is no expression or no value in the
Salary:3500 statement, then the function will return the None
object
Syntax:
return [expression list ]

Elangovan 9677515019 Page 3


12 CS Guide R.M.K.MATRIC.HR.SEC.SCHOOL - 601206

15.What is meant by scope of variable? Mention its 16.What happens when we modify global variable
types. inside the function
15.Explain the types of Scope of Variables  Thrown an error because,
 Without using the global keyword we cannot
Local Scope modify the global variable inside the function.
 A variable declared inside the function's body or in  but we can only access the global variable
the local scope is known as local variable. Example:
c = 10 # global variable
Rules of local variable def add():
 It can be accessed only within the function/block. global c
 local variable is created inside the function/block. c=c+2
 A local variable only exists while the function is print(c)
executing. add()
 The formal arguments are also local to function. output: 12
Ex 17. Write a Python code to heck whether a given year
def loc(): is leap year or not.
Y=4 y=int(input("Enter a Year : "))
loc() if y%4==0:
print(y) print(y," is a leap year")
else:
Output print(y," is not a leap year")
error
The above error occurs because y is a local variable. 18.Explain the following built-in functions.
id()
Global Scope  Returns address of an object
 A global variable, can be used anywhere in the  Syntax: id(object)
program.  Ex. a=15.2
 It can be created by defining a variable outside the Print(id(a)) # : output : 134526789
function/block. chr()
Rules of global Keyword  Returns Unicode character for the given ASCII
 To define a variable outside a function, it’s global value
by default.  Syntax: chr(x)
 global keyword used modify the global variable  Ex.x=65 print(chr(x)) #output : A
inside a function. round()
 Use of global keyword outside a function has no  Returns the nearest integer to its input
effect  First argument is used to specify the value to be
Example: rounded
c = 10 # global variable  Second argument is used to specify the number
def add(): of decimal digits
global c  Syntax : round(number,[,ndigits])
c=c+2  Ex. x=17.89 print(round(x,1)) #output : 17.9
print(c) type()
add()  Returns the type of object.
output: 12  Syntax: type(object)
 Ex.X=15.8 type(x) #output <class ‘ float’>
pow()
 Return the computation of ab i.e a**b
 Syntax: pow(a,b)
 Ex .pow(3,2) # output 9

Elangovan 9677515019 Page 4


12 CS Guide R.M.K.MATRIC.HR.SEC.SCHOOL - 601206

19. Write a Python code to find the L.C.M. of two 22.Explain about format() function
numbers.  Returns the output based on the given format
x=int(input("Enter first Number..."))  Syntax: format(value,[format_spec])
y=int(input("Enter second Number..."))  Example : x=14 print(“the value id
“,format(x,’b’)
def lcm(x,y): Binary format_spec - > b
i=max(x,y) octal format_spec - > o
fixed point notation: format_spec - > f
s=min(x,y)
i=1 23.Explain mathematical function with an example

while(True): Sqrt()
if i % s == 0:  Returns the square root of x
 Syntax: sqrt(x)
return i  A=25 sqrt(a) output : 5
i+=1 ceil() floor()
Returns the smallest Returns the largest
print(lcm(x,y)) integer >= x integer <= x
20.What is Composition in functions? math.ceil(x) math.floor(x)
 The value returned by a function may be used as an X=26.7 y=-26.7 z=-23.2 X=26.7 y=-26.7 z=-23.2
argument for another function in a nested manner. Print(math.ceil(x)) = 26 Print(math.(x)) = 27
This is called composition. Print(math.ceil(y)) = -27 Print(math.ceil(y)) = -26
 For example, if, we take the input string Print(math.ceil(z)) = -24 Print(math.ceil(z)) = -23
 using the function input() and apply eval() function
to evaluate its value, 24..Differentiate ceil() and floor() function?
for example:
>>> n1 = eval (input ("Enter a number: ")) ceil() floor()
Enter a number: 234 Returns the smallest Returns the largest
>>> n1 integer >= x integer <= x
234 math.ceil(x) math.floor(x)
21.Explain some Built-in and Mathematical functions X=26.7 y=-26.7 z=-23.2 X=26.7 y=-26.7 z=-23.2
in python Print(math.ceil(x)) = 26 Print(math.(x)) = 27
Print(math.ceil(y)) = -27 Print(math.ceil(y)) = -26
abs() Print(math.ceil(z)) = -24 Print(math.ceil(z)) = -23

 Returns an absolute value of a number


 Syntax: abs(x)
 X=-45.7 abs(x) output : 45.6
bin()
 Returns a binary strings with prefixed 0b
 Syntax:bin(x)
 X=15 bin (x) output: 0b1111
Min()
 Returns the minimum value in the list
 Syntax: min(list variable)
 M=[12,23,4,5,6] print(min(m)) output : 4

Elangovan 9677515019 Page 5


12 CS Guide R.M.K.MATRIC.HR.SEC.SCHOOL - 601206

www.nammakalvi.in

UNIT CHAPTER 8 STRINGS & STRING MANIPULATION


II ALGORITHMIC STRATEGIES

6.Explain about string operators in python with


1.Define String. suitable example
 String is a data type in python.
 It is used to handle array of characters. (i) Concatenation (+)
 String is a sequence of Unicode characters consists  Joining of two or more strings is called as
of letters, numbers, or special symbols enclosed Concatenation.
within single, double or even triple quotes  The plus (+) operator is used .
 Strings are immutable in 'Python', Example
 Can not make any changes once you declared >>> "welcome" + "Python"
'welcomePython'
2.Do you modify a string in Python? (ii) Append (+ =)
 Strings are immutable in 'Python',  Adding a new string with an existing string.
 Can not make any changes once you declared  The operator += is used.
 If you want to modify the string, completely Example
overwrite a new string value on the existing string >>> x="Welcome to "
variable. >>> x+="Learn Python"
3.How to replace a particular character in python? >>> print (x)
 replace() to change all occurrences of a particular Welcome to Learn Python
character in a string (iii) Repeating (*)
 syntax: replace(“char1”, “char2”)  The multiplication operator (*) is used to display a
 Ex. >>>a=”ELANGO” string in multiple number of times.
>>>print(a.replace(“E”,”I”) Example
>>> ILANGO >>> str1="Welcome "
4.How will you delete a string in python? >>> print (str1*4)
 python will not allow deleting a particular character Welcome Welcome Welcome Welcome
in a string.
 we can remove entire string variable using del (iv) String slicing
command.  Slice is a substring of a main string.
Syntax: del(string variable)  Slicing operator [:] with index or subscript value is
Ex.>>> a=”ELANGO” used to slice one or more substrings from a main
>>>del(a) string.
5.How python accessing characters in a string? General format of slice operation:
 Once you define a string, python allocate an index variable[start:end]
value for its each character.  start - beginning index default is 0
 These index values are otherwise called as subscript  end - last index value of a character in the string as
 which are used to access and manipulate the n-1 .
strings.
 The subscript can be positive or negative integer >>> s="ELANGO"
numbers. >>> print (s[0]) #output : E
 The positive subscript from 0 to n-1, >>> print (s [1:5]) #output :LANG
 The negative index from the last character to the >>> print (s [:5]) #output:ELANG
first character in reverse order begins with -1. >>> print (s [3:]) #output: GO

Elangovan 9677515019 Page 1


12 CS Guide R.M.K.MATRIC.HR.SEC.SCHOOL - 601206

(v) Stride when slicing string Formatting characters:


%c Character
 In the slicing operation, a third argument as the %d Signed decimal integer
stride, (or) %i
 which refers to the number of characters to move %s String
%u Unsigned decimal integer
forward after the first character is retrieved from
%o Octal integer
the string. %x or Hexadecimal integer
 The default value of stride is 1. %X
Example %e or Exponential notation
>>> s = "Welcome to learn Python" %E
%f Floating point numbers
>>> print (s [10:16])
%g or Short numbers in floating point or exponential
learn %G notation.
>>> print (s [10:16:4])
r
9.Write a short note on Escape sequence in python
>>> print (s [10:16:2])
and list them
er
Escape sequences starts with a backslash .
>>> print (s [::3])
Wceoenyo
 If you specify a negative value, it prints in reverse
order
>>> print(a[::-1])
OGNALE

7.What will be the output of the given python


program?
str1 = "welcome"
str2 = "to school"
str3=str1[:2]+str2[len(str2)-2:]
print(str3)

#output: weol

8.Write a short note on String Formatting operators.


10.What is the use of format( )? Give an example.
 % is called string formatting operator.
 The format( ) function used with strings is used for
 It is used to construct strings, replacing parts of the formatting strings.
strings with the data stored in variables  The curly braces { } are used as placeholders or
replacement fields which get replaced along with
Syntax: format( ) function
(“String to be display %var1 and %var2” % (var1,var2))
Ex.
Ex. a,b=10,5
name = "ELANGO" print(“The sum of {} and {}is {}”.format(a,b,(a+b))
mark = 98 #output: The sum of 10 and 5 is 15
print ("Name: %s and Marks: %d" %(name,mark))
#output: Name:ELANGO and Marks:98

Elangovan 9677515019 Page 2


12 CS Guide R.M.K.MATRIC.HR.SEC.SCHOOL - 601206

11.Write a note about count( ) function in python. >>> a="ELANGO"


 Returns the number of substrings occurs within the >>> a.find('A')
given string. 2
 Substring may be a character. isalnum()
 Range is optional. Returns ‘True’ if the string contains only letters and
numbers otherwise ‘False’.
 Search is case sensitive.
Syntax: Variable.count(string,start,end)
isalpha()
Returns ‘True’ if the string contains only letters
>>> a="ELANGOVAN"
>>> print(a.count('E'))
otherwise ‘False’
1 isdigit()
>>> print(a.count('AN')) Returns ‘True’ if the string contains only numbers
2 otherwise ‘False’
>>> print(a.count('A',0,5)) lower()
1
Returns the string in lowercase.
12.Explain Membership Operators with an example.
upper()
Returns the string in uppercase.
 The ‘in’ and ‘not in’ operators are called as
islower()
Membership Operators.
Returns ‘True’ if the string is in lower.
 It can be used with strings to determine whether a
isupper()
string is present in another string.
Returns ‘True’ if the string is in upper.
Example:
title()
a=input ("Enter a string: ")
Returns a string in the case.
b="chennai"
swapcase()
if b in a:
It will change a string in opposite case.
print ("Found")
else:
print ("Not Found")
#output:
Enter a string: Madras
Not Found
Enter a string: chennai
Found

13.List and explain some Built-in String functions


len(str.variable)
 Returns the length of the string.
a=”ELANGO”
print(len(a)) -> #output: 6
capitalize()
 to capitalize the first character of the string.
a=”elango”
print(len(a)) -> #output: Elango
center(width,fillchar)
 return a string at center to a total of width filled by
fillchar that do not have character.
>>> a="ELANGO"
>>> print(a.center(10,'*'))
**ELANGO**
find(‘str’,[start,end])
 It is used to find the sub string of the given string
 It returns the index at which the sub string starts.

Elangovan 9677515019 Page 3


12 CS Guide R.M.K.MATRIC.HR.SEC.SCHOOL - 601206

www.nammakalvi.in

Elangovan 9677515019 Page 4

You might also like