0% found this document useful (0 votes)
49 views21 pages

Adobe Scan Oct 17, 2024

Uploaded by

singhharsh2485
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)
49 views21 pages

Adobe Scan Oct 17, 2024

Uploaded by

singhharsh2485
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/ 21

3

CHAPTER
Functions

IMPORTANT TERMS AND DEFINITIONS


perform.
Function is a group of statements or subprogram/ subroutines with a well-defined task to
1. Function in Python. A
Built-in functions and User Defined functions.
In Python, we have two types of function:
2. Advantages of Functions: modular
(a) Reusability of code (b) Programming becomes
(c) Clarity in the program (d) Easy to debug
interpreter. These functions
Python Built-In Function. These are the predefined functions which are stored in python
3. Built-in method.
can be categorised in two ways: Built-in or function name. Example
Built-in Functions. These are the functions for which we just have to call the function with its
available for most of the data
some built-in function: len(), max (), min), print(), input(0 etc. These functions are
of
objects in Python.
>>>lst=[1, 2, 3,4, 5]
>>> max(lst)
5 library of python.
method because these are available in various classes or
Built-in methods: These are actually known as
For example :
To use these methods, we need to import the library.
>>> import math
>>>math. sqrt(36)
6.0
>>> import Iandom
>>>random. randint (5,10)
6
statement. For example:
Python also consist of built-in modules for which do require to import
>>>lst= [1, 2,3,4,5]
>>>lst. reverse()
>>>lst
(5, 4, 3, 2, 1]
Note:
Functíons are the independent piece of script (code).
Methods are the piece of script, available in the clasS and accessed by <class name> or <object>,
of auser
4. User Defined Function. A functiOn is a n¡med group of statements to perform a specific subtask. Example
defined function is given below:
Syntax of the function:
any):
def <function name> (argunent if #function header
<statement1>
<statement2>
Function Definition or Body

return (if required)


Functions 65
<function name>(parameter if required)) #calling
Example of a function
def hello():
function header (Function Name)
nm=input("Enter youI name:") Function body/block
print( "Hello", nm)

print(" ") #1 function call


prünk:(" Helto, A)
hello(* #2
print (" Done") #3
hotlol)
In this function: print ("one
def hello(): is the function header(Name).
" def is a keyword a function is defined. Any function definition in Python
has to be marked with the keyword def.
hello is the function name. A function name can be any valid identifier.
Empty parentheses () indicate that this function does not accept any parameter
from the user. The concept of
parameters will be explained soon.
Colon (:) marks the end of function header
return statement within function body is optional, you may or may not return a value from a method.
Note: It may return more than one value that.
5. The Function Body. The statements indented under function header(name) constitute the
function body. The statements
in the function body are executed when the function is called.
6. Function Call. A function executes only when it is called/invoked. In the ab0ve program, hello) is the function call
statement.
7. Function calling process
def function(:)

Function call will pass


the control to function return

definition # main script

function(0 After completing the


print() script function will pass
the control to main
soript.
8. Multiple calling functions
,def function 1():
Function I call by
function 2
Function call will pass
the control to function return

definition def function2():

function 1) #call

return

# main script
After completing the
functionl) script function will pass
print the control to main
script.
66 ogether itk Conputer Science (Python)-12
9. Scope (of a variable). Scope of' avariable refers to
the Output produced by this module is:
part of the module wherc it can be used. A variable can a= 5
have local scope or global scope. a= 50

10. Local Scope. Avariable defined inside a function can a= 5


be used inside that function only, and is called a local Note:
variable. A local variable can be used only inside the () we can always use the value of any global variable
function in which it is declared. It cannot be used in afunction, if the function does not have a local
anywhere else in the module. For example: variable in that name.
def print_even():
n=int (input ("Enter an integer:")) (ii) Ifwe try to assign a value toa variable in a function,
n=abs (n) then the function willcreate the variable as a local
print ("First, n," even natral numbers are:") variable, and any global variable which has the
for i in range (1, n+1): same name cannot be used in that function.
print (2*i, end=" ") 13. Global Keyword. It allows to modify the variable outside
print() of the current scope. It is used to access the global
variable inside any module /function we can use global
print_even() keyword. For example:
print ("Printed",n, "even natural numbers") a = 5 # global variable
Here an Name error is displayed on excution as the def display():
variable 'n' is not defined. It has local scope, as defined global a
in the function print even() a * 2 # increment by 2
11. Global Scope. A variable defined outside any function print ("Display() inside:" a)
is called a global variable. A global variable, after
its declaration, can be used anywhere in the module. display ()
For example: print("Global access:", a)
def area_peri(): output:
area=l*b
Display() inside: 10
perimeter=2* (1+b) Global access: 10
print("Length of rectangle: ",1) 14. Parameter. The variable(s) which are used in method
prínt ("Breadth of rectangle: ",b) definition, are known as parameter(s).
print("Area ",area)
print("perimeter =",perimeter) Argument : These are the data values which we pass
in calling method. They contain the actual value.
l=eval(input ("Enter the length of rectangle:")) For example:
b=eval(input ("Enter the breadth of rectangle:")) def total(a, b): # a and b are parameters.
area_peri() C=a+b
Here the variable I and b is defined globally so it is used print("Addition is ",c)
within area-peri().
12. Updating a global variable in a function. We can use X=10
the value of a global variable in any function, but we y=20
cannot change its value. If we try to change the value total(x, y) # X and v are arqumentS.
of aglobal variable in a function, Python consider it as
a local variable. This is shown in the following module: 15. Formal Parameter. The parameter specified in the
a=5
function header is called aformal parameter. For example
def new_value ():
in a method def display(x,y):, here xand y are formal
a50 parameter.
prínt("a=",a) 16. Actual Parameter. The value/expression specifiedini
(orargument).
function call is called an actual parameter
print("a-",a) For example: In a method call display(2,3), 2 andpassed
new value()
actual parameters(arguments) whose value will be
print("a:", a) to the calling function.
Functions 67
17. Mutable object. These are the objccts
which can be formal parameter, rather the formal parameter becomes
changed after its creation: For example: List,
and set. Dictionary a reference to the actual parameter. Thus, any change
in the value of formal parameter is reflected in actual
18. Immutable Object. These are the objccts
which cannot parameter also. This can be observed from the following
be changed after its creation. For
example: int, float, program:
string and tuple. def val_ref (n, nums):
Note: AS such, there is no concept of Call by value and print("Values passed to the function: ")
Callby reference of the variable in python, it works with print("\tn =",n)
the objects which are mutable or immutable. print("\tnums =", nums)
n += 5
19. Parameter passing in case of immutable objects. The
formal parameters are treated as local variables in nums.append("new")
print("Values in the function, after change: ")
functions. Therefore any change in the values of a
formal parameter does not have any effect on the print("\tn ",n)
print("\tnums =", nums )
corresponding actual parameter. This can be observed k=20
from the following program and its output:
seq=[1,2, 3, 4]
def change_it (n): print ("Before function call: ")
print (n) print ("\tk =",k)
n+=5
print ("\tseq =", seq)
print (n)
val_ref (k, seq)
print("After function call: ")
a=10
print ("\tk =",k)
b=20
print ("\tseq =",seq)
change_it(a) # Function_call with the output:
parameter value a=10 Before function call:
print("a ",a) # Functin call with parameter
k = 20
value b=20
seq = [1, 2, 3, 4]
change_it(b)
Values passed to the function:
print ("b=",b) n = 20
Output: nums = [1, 2, 3, 4]
10
Values in the function, after change:
15 n = 25
a = 10
nums = [1, 2, 3, 4, 'new']
20 After function call:
25 k = 20
b= 20
seq (1, 2, 3, 4, 'new']
20. Pararmeter passing in case of mutable objects, Likeany 21. Positional Argument, Positional Argument - These are
other variable, we can also pass strings, tuples, and the arguments which need to be included in the proper
dictionarics as parameters to functions. Passing lists position or order.
and dictionaries as parameters need special treatment Example
because these are mutable objects, unlike numbers and def display(a, b):
strings. print(a, b)
When a simple variable is passed as a parameter, #Main
the values of actual parameter is copied into formal X=9
parameter. After that formal parameter is treated as a y*10
local variable and any change in it's value has no effect display (x,y)
on the coresponding actual parameter. But in case of Now, x will match to a and y will match to b, thats
Iists no value is passed from actual parameter to the called as positional argument.
68 Together ewitko Computer Science (Python)-12
22. return values. When the function completes its task. Then output :
it returns the calculated function value to the calling Sum is 5

function, through the keyword return.


#arguments passed as tuple
For example:
def fact (n): def display (*names):
# to calculate and return the factorial of n for name in names:
f-1; print("Welcome", name)
for i in range (2,n+1): print("Welcome again", names[31)
f*=i
return f display("Raj", "Naveen", "Nidhi", "Sasmita")
23. Types of function arguments in Python. There are three output:
types of Python function arguments using which we can Welcome Raj
call a function. Welcome Naveen
Welcome Nidhi
(a) Default Arguments
Welcome Sasmita
(b) Keyword Arguments Welcome again Sasmita
(c) Variable-length Arguments 27. Return. Return is the keyword which is used at the
24. Default argument. A default argument is a value provided end of the function definition. If the return statement is
in function header (declaration) which is automatically without expression, the special value None is returned.
In python we can return the multiple values or an object.
assigned by the interpreter if the caller of the function
does not provide a value for the argument. An object can be a numerical value, like an integer or a
float. But it can also be a list or a dictionary. Suppose
For example: we have to return, three integer values, we can return a
'Default Argument" list or a tuple with these three integer values. Thus, we
def display (x, y="Hello"): can indirectly return multiple values.
print (x, " and , y)
display( "Without default value", "bye!!! ")
Example 1:
display("Use of default") #Single value return
def fact(n=5):
Output: f-1
Without default value and by!!
Use of default and Hello for i in range(1, n+1):
f-f*i
25. Keyword Arguments. On calling a function with some return #Returning single Value
values, these values get assigned to the arguments print (fact(7) ) 'Function call and
according to their position. returning values for direct print()"
#example of keyword cal1ling argunents ans=fact() #Default arugment calling
def disp (name1, name2): and storing information in variable" '
print (namel, name2) print (ans)
disp(nane2-"Sagar", name1="Rachna") Output: S040
output : 120
Rachna Sagar #Multiple value returns
26. Variable-length Arguments. Some times while making the def hello() :
progran we are not sure about the number of arguments, str = "welcome"
1 = 40
so python defines the variable length arguments. With
(*) asterisk symbol we can use this concept. return stÉ, 1; # Return tuple

Example: str, a = hello() "'Assign returned tuple


def add(*x): can also be list or dictionary"
#using the subscript we can write this print (str)
z=x{0]+x[1] print (a)
print ("Sum is",z) Output: welcome
add(2,3)
40
Functions 69

COMMON INSTRUCTIONS
Assertion and Reason Questions
(a) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct
explanation of Assertion (A)
(b) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct
explanation of Assertion (A)
(c) Assertion (A) is true but Reason (R) is false
(d) Assertion (A) is false but Reason (R) is true

SOLVED QUESTION BANK

Objective Type 6. What is the syntax for defining default parameters


in a function?
Questions 1Mark
sa) def function name (parameter 1 = default1,
1. Which type of functions are already provided by the parameter2-default2):
programming language?
(6) def function name (parameter 1 , parameter 2 =
(a) User-defined functions default2):
(b)>Built-in functions
(c) Module functions (c) def function name (parameter 1 = default 1,
(d) None of the above parameter2):
Ans. (b) (d) def function name (parameter 1 = default 1,
2. Which type of functions are defined in external files? parameter2-default2,):
(a) User-defined functions Ans. (a)
(b) Built-in functions 7. What is the difference between aparameter and an
c) Module functions argument?
(d) None of the above (a) Parameters are input passed to the function, while
Ans. (c) arguments are variables defined inside the function
3. How do you create a user-defined function in Python? ) Parameters are variables defined inside the
(af def function name): function, while arguments are input passed to the
(b) function name): function
(c) function name(0) (c) Parameters and arguments are the same thing
(d) define function name): (d) None of the above
Ans. (a) Ans. (b)
4. What is a parameter in a function? 8. What is the difference between positional parameters
saj The input passed to the function and keyword parameters?
(b) The output returmed by the function (aYPositional parameters are specified by their position
(c) The name of the function in the function call, while keyword parameters are
(d) The type of the function specified by their name
Ans. (a) (b) Positional parameters are specified by their name
5. What is an argument in a function? in the function call, while keyword parameters are
(a) The input passed to the function specified by their position
(b) The output returned by the function (c) Positional paranmeters and keyword parameters are
(c) The name of the function the same thing
(d) The type of the function (d) None of the above
Ans. (a) Ans. (a)
70 Taptker nte Computer Science (/yhon)12
Can a functien return multiple values? (b) Positional parameters must OCCur to
Default parameters
the right of
(b) No
(c) Positional parameters must OCCur to
Ans. (a)
Default parameters
the left of
16. What is the keyword sed to return a value from a
function? (d) All parameters to the right of a Default
(a)pass (6) break must also have Default values. parameter
() continue Ans. (b)
16. Which of the following is not a
Ans. (c) function/methodf
the random module in Python
Which of the following is not correct in context of (CBSE 2021|
scope of variables? |CBSE 2021] (afandfloat () (b) randint())
(c) global keyword is used to change value of a global (c) random() (d) randrange()
variable in a local scope Ans. (a)
(b) local keyword is used to change value of a local 17. What will be the output of the following Python
variable in a global scope code?
[CBSE 2021)
(c) globalvariables can be accessed without using the V = 25
global keyword in a local scope def Fun (Ch):
(d) local variables cannot be used outside its scope V=50
ARs. (b) print (V, end=Ch)
12 Which of the following is the use of idQ0 function in print (V, end="*")
Python?
Fun ("!")
Aa) ldreturns the identity of the object print (V)
(b) Every object doesn't have a unique id (a)r25*50! 25 (6) 50*100! 100! 100
(c) All of the mentioned (c) 25*50!100!100 (d) Error
(d) None of the mentioned Ans. (a)
Ass. (a) 18. What is the output of the function:
13 What will be the output of the following code : len(["hello" , 2,4, 6])
print type(t ype(int)) á) 4 (b) 3
(a) type 'int' (b) type 'type' (c) Error (d) 6
(e) Emor (d) null
Ans. (a)
19, What will be the output of the following code:
For a funetion header as follows: ICBSE 2021| import math
def Celc(x, Y20) abs(math. sqrt(25))
Which of the following function calls will give an (a) 5 Ab) 5.0
Error?
(e) ertor () No output
(u) Cair15, 25) (b) (al (X-15, Ye25)
(e) Calc(Y-25) (d) Calc(X-25) Ans, (b) below?
shown
20. What is the output of the funetions
I5. Waich of the following is not correet in context Min(max(False, 3, -4),2,7)
of Positional aud Defauit parameters iu Python (a) -3 (b) 4
fuactios? jCBSE 20211 (cd) False
( True
iu) etauk parancters ust EUr 0 the right of
PositonaB pararneters Ans. ()
Functions 71
21. What is the output for the following Python code? M[i] //- 3
def ListChange(): L=[ 25,8,75, 12)
for i in range (len(L)): ChangeVal(L,4)
if L[i]%2 == 0: for i in L :
L[i]=L[i]2 print(i, end='#)
if L[i]%3 == 0: Ans, 5#8#5#4#
L[i]=L[1]*3 28. Find and write the output of the following python
else: code:
L[i]-L[i]*5
L = [2,6,9, 10] def Cali(P=40,0=20):
P=P+Q
ListChange()
for i in L: Q=P-Q
print(P, 'q',@)
print(i, end="#") return P
7(a) 4#12#27#20# (6) 6#18#27#50#t R=200
Wc) 20#36#27#100# (d) ErOI S-100
Ans. (c) R=Call(R,S)
22. Assertion (A): Default parameters are used in Python print (R,'@',S)
functions to specify values for arguments that are not S=Call(s)
explicitly passed by the caller. print (R, 'a',s)
Reason (R): This allows the function to have a default Ans. 300 200
behavior when the caller does not provide a value for 300 @ 100
an argument.
Ans. (a) 120 @ 100
23. Assertion (A): A function can return multiple values in 300 @ 120
Python. 29. Define the following terms:
Reason (R): This is achieved by returning a tuple
(a) Function, (6) Scope of a variable,
containing multiple values. (c) Local variable
Ans. (a) (d) Global variable
(e) Parameters () Arguments
24. Assertion (A): A variable declared outside a function Ans. () Function: A Function is a group of statements or
has global scope in Python.
subprogram/ subroutines with a well-defined task
Reason (R): This means that it can be accessed and to perform.
modified from inside any function.
Ans. (a) (b) Scope of a variable: Scope of a variable refers to
the part of the module, where it can be used.
25. Assertion (A): Alocal variable defined inside a function
has local scope in Python. (c) Local variable: A local variable is a variable
which is defined inside a function, without keyword
Reason (R): This means that it can only be accessed
and modified from inside the same function. 'global'. A local variable can be used only in the
Ans. (a) function in which it is declared.
26. Assertion (A): A function can have both positional and (d) Global variable: A global yariable is a variable
keyword arguments in Python. which is defined outside any function, or defined
inside a function with global keyword. A global
Reason (R): This allows the caller to specify some
arguments by position and others by name. variable can be used throughout the module after
Ans. (a) its declaration.
(e) Parameters: Parameters (Also called formal
Short Answer
parameters) are the variables defined in function
Type Questions 2/3 Marks header. Parameters represent the values/references
to be received from function çall.
27. Find and write the output of the following python
code: For example, def display (a, b):
def ChangeVal(M, N): 2175 () Arguments: Arguments (Also called actual
for i in range (N): parameters) are the expressions used during
if M[i]%5 0 : function call to pass the values/references to the
M[i] //- 5 function being called.
if M[i]%3= 0: For example, display (10, 20)
72 Togecker wekO Computer Science (Python)-12
30. Write the use of the following keywords: Mutable data Immutable data
(c)
objects objects
() def (ii) return
Mutable data objects| Immutable data objects
Ams. () Keyword def is used to define functions in Python. can be modified after cannot be modified
once they are created.
For example def Hello(): their creation.

(i) Keyword return is used to return a value from a Mutable data objects Immutable data objects
functions
function. are passed to functions are passed to
with reference. with value.
For example, return 10
Examples of mutable Examples ofimmutable
3. What is the use of keyword global? data objects are: lists data objects are:
and dictionaries. integers, floats, strings,
Keyword global is used to:
tuples.
(i) Specify the global variable(s) which will be used
in the function even if their values are changed in 33. Rewrite the following python code after removing any/
the function.
all syntacticalerrors with each correction underlined:
(a) def guess ()
(i) Tocreate global variable(s) in the function. print ("Hello")
32. Differentiate between: print (a)
a-5
(a) Formal parameters and Actual parameters
var-2
(6) Local variable and global variables quess
(c) Mutable and immutable data objects (6) def add:
total=0
AnS. (a) Formal Parameter Actual parameter
n=input("Enter a number: "
Specified in the Specified the
m=input("Ente another number:)
function header. function call.
total=m+n
Can be a variable only Can be a variable,
constant, or any valid print total
expression add()
For example: (c) Def func (a+b):
display (a): # a is fOrmal parameter tot-a+b
def
a = a * 2 # increment by 2 print(tot)
m=10
print("a=", a)
n=20
x=5
display (x) #x is actual parameter fun (m, p)
(d) function f1(b):
Local yariable Global variable if b>0 then:
(b)
return"Positive"
Defined insíde a Defined outside any
function without using function, or inside else return "Not Positive"
the keyword global. a function using the m=int (input("Enter an number: "))
keyword global. msg=f1()
Can be used only Can be used throughout print (msg)
inside the function in the module, after its (e) def isMultiple (a b):
which it is declared. declaration.
if a%b=0:
For example: return true
a 5 # global variable else return false
def display () : m=int(input("Enter first number: "))
a = a * 2 # Local Variable n=int(input ("Enter second number: "))
print ("Display() inside:", a) if isMultiple [m, n]:
display() print ("m is a multiple of n")
a multiple
of n")
else print (m, "is not
Functions 73

) find HCF (a, b): m=int(input("Enter first number: "))


h=a n=int (input("Enter second number: "))
while b%h! =0 OR a%h!=0 h=HCF (m, n) # erOI 4
h-=1 print ("HCE =",h)
return h
m=int(input("Enter first number: ")) 34. What will be the output of the following Python code?
n=int (input("Enter second number: ")) X = 50

HCF (m, n) =h def func():


global x
print("HCE ="h)
print('x is', x)
Ans. (a) def guess (): # erroI 1
X = 2
print ("Hello")
print('Changed global x to', x)
a=5 # errOI 2
print(a) # error 3 func ()
var=2 print('Value of x is', x)
guess() # errOI 4 Ans, x is 50
(6) def add(): # errOI 1 Changed global x to 2
total=0
Value of x is 2
n=input("Enter a nunbeI:") # error 2
m=input("Enter another number: ") 35. What will be the output of the following Python code?
# error 3 def say (message, tines = 1):
total=M+n print (message * times)
print (total) # errOI 4 say("Hello')
add() say('World', 5)
(c) def func(a,b): # error 1,2 Ans. Hello
tot=a+b WorldWorldWorldWorldWorld
print (tot)
m=10
36. What will be the output of the following Python code?
n=20 def func(a, b=5, C=10):
# error 3,4 function addition. txt
func (m.n)
(d) def f1(b): # erIOr 1 print('a is', a, 'and b is', b, 'and c is', c)
if b>0:
# erIOr 2 func (3, 7)
return "Positive" func (25, c = 24)
else: return "Not Positive" # error 3 func(c = 50, a = 100)
Ans. a is 3 and b is 7 and c is 10
m=int (ínput ("Enter an number: ")) a is 25 and b is S and c is 24
msg-f1(m) # error 4
a is 100 and b is 5 and c is 50
print (nsg)
(e) def isMultiple (a,b): # error 1
37. What will be the output of the following Python code?
# errOr 2
if a%b==0: def £1():
return True # err0r 3 X=15
else: return False # error 4
print(x)
m=int(input("Enter first number: "))
X=12
n=ínt(input ("Enter second number: "))
f1()
if isMultiple(m, n): # err0r 5
Ans, 15
print("m is a multiple of n")
else:_print (m, "is not a multiple of n") 38. What will be the output of the following Python code?
# errOr 6 X=12
) def HCF(a, b): # error 1 def f1(a,b=x) :
h=a print(a, b)
whíle b%h! =0 0r a%h! -0: # error 2, 3 X=15
h-1 f1(4)
return h Ans, 4 12
74 Together wek Computer Science (Python-12
39. What will be the output of the following Python code? print('y = '.y)
def f(): print("z =',z)
global a X=5

print (a) func (10)


a = "hello" Ans. Global x= 5
print (a) Local x =7
a = "world" y=15
£() z =-3
print(a)
Ans. world
43. Write the output of the following Python code:
def func (x, y=100):
hello temp = X + y

hello X += temp
if(y!=200):
40. Write the output of the following Python code : print(temp, x, x)
def Update (X=10): a=20

X += 15 b=10
func (b)
print('X = ', x) print(a, b)
X=20
func(a, b)
Update() print (a, b)
print("'X = ', X) Ans. 110 120 120
Ans. X = 25 20 10
X= 20 30 50 50
20 10
41. Write the output of the following Python code:
def div5 (n): 44. Write the output of the given code:
if n%5==0: def Convert (0ld) :
return n*5 l=len (0ld)
New="n
else:
for i in range (0,1):
return n+5
if 0ld[i].isupper():
def output (m=5): New=New+0ld[i]. lower()
for i in range (0,m): elif 0ld [i].ilower () :
print (div5 (i), 'e' , end="") New=New+0ld[i].upper()
print () elif 0ld [i].isdigit() :
output (7) New=New+"*
else:
output()
output (3) New-New+"%"
return New
Ans. 0@6 @7 @8 @9 @25 @11 @ 0lder-"InDIag2020"
0 @6 @7 @8 @9 @ Newer=Convert (0lder)
print ("New string is :" Newer)
0@6 @7 @ Ans. New string is :
42. Write the output of the following Python code:
iNdiA%****
45. Write the output of the
def func (b): given code:
qlobal x def display (n):
print('Global x=', x) Sum=5
y = X+ b i = 1
X = 7 while i<-n:
Z X-b Sum += j
print("Local x ',x) i +=5

Sum=sum-2
Functions 75

print("Value =", sum," i: ",i) 48. Write the output of the given codex=
X = 30 7 #Global Variable
display (x) def display():
Ans. Value = 74 /= 31 global x
X=10
46. Write the output of the given code:
if x>=7:
X = 15
y=9
def change(): print (y)
#using a global keyword display()
global x print (x)
# increment value of a by 5
Ans, 9
X X + 5
10
print("Value of x inside a function :", x)
change() 49. Find the errors and rectify the script.
print ("Value of x outside a function :", x) def show(n, string='Good' k=5):
Ans. X = 15 return display (string)
def change(): return n
#using a global keyword def display (string)
global x 4return string==str(5)
# increment value of a by 5 print (show("Children's Day"))
e'):) Tree i))
X = X + 5 print(display (string='true'
print("Value of x inside a function :", x) print (show(5, "Good") )
change() Ans. Correct Code
print("Value of x outside a function :", x)
# Python program to modify a global
def show(n,string='Good', k=5):
return display (string)
# value inside a function
return n # Cannot return 2 values
X = 15
def display (string) :
def change(): return string==str(5) # indentation
#using a global keyword
global x
# increment value of a by 5
print (show("Children's Day"))
X = X + 5
print (display(string='true'))
# to be removed
print("Value of x inside a function :". x) print (show(5, "Good"))
change ()
print("Value of x outside a function :", x) 50. Find the output:
Value of x inside a function : 20 def show(n,string=' Good' ,k=5):
Value of x outside a function : 20 return display (string)
return n
47. Write the output of the given code
def Check(K, L=70): def display (string):
return string==str(5)
if (K>L):
K-=L print (show("Children's Day"))
else: print (display(string='true'))
K+=L print (show(5, "Good") )
M=100 Ans, False False False
N=40
51, Write a function Display) which do not accept any
Check(M, N) parameter and return none.
print (M, "#", N)
Ans. def display(): def display ():
Check(M)
print (N,"*",M)
Ans. 100 # 40
printl) print()
return none
print()
print (display () )
40 # 100 print(display () )
76 Togetker ucek Computer Science (Python)-12 age and
(c) A function Vote Casting) will acceptsvalue.
52. Answer the following questions based on the given citizen as parameter returns
Boolean
parameters and
seript/code. (d) A function Show ) accepts no
def show(a) : returns nothing.
a=10
Ans. (a) def ADD (a, b) :
a=a+3 (b) def ADD (a, b):
return a
return a
b=100
citizen):
res-show(b) (c) def Vote_Casting(age,
False
(a) Name the variable used as parameter. return True or retUIn
(6) Name the variable used as an argument (d) def Show() :
(c) Write function header statement. return None
() Which statement will return a value? script/code
(e) Name a local variable(s). 55. Write the output of the following
) Name a global variable(s). (a) def show5():
(e) Write function call statement. print ("Hello")
(h) Variable 'a' will return the value to variable show5a()
def show5a():
() Name formal parameter print ("Bye")
Ans. (a) a show5a()
(b) def show5():
(6) b print ("Hello")
(c) def show(a) : show5a()
(d) return a def show5a():
(e) a print("Bye")
show5()
(g) res=show(b) Ans. (a) Bye
(6) Hello
(h) res
() a Bye
given 56. Write a program to create the list and do the following
53. Answer the following questions based on the operations using the predefined functions.
seript/code.
def show4 (a,b): To print sum of all element of the list
print (a+b) To find maximum element of the list
X=show4(10, 15) To find minimum element of the list
print (x) To find the length of the list
(a) Name local variable(s).
To sort the list in ascending order
(b) Name global variable(s).
is built-in function. To sort the list in descending order
(c) [FileName:ch-datas\Q14|
is user-defined function.
(d)
1
(e) Name actual parameter(s). Ans. list = input('Enter the sorted list of numbers:
) Name formal parameter(s). list = list.split()
Ans. (a) a, b
list [int (x) foI X in list]
(b) x print (list)
(c) print(0 print(type (list)
(d) show4) print ("Sum of the list", sum(list))
max(list))
(e) 10,15 print("Maximum element in the list"., min(list))
() a, b print("Minimum element in the list"",
S4. Write the function definition for the following: print ("Length of the list", len(list))sorted(list))
order"",
(a) A function ADD) accepts two parameters. print ("Sorted list in ascending
(6) A function ADD) accepts two parameters and print ("Sorted list in descending
returns a single value. order",sorted(list.reverse=True))
Functions 77
57. WAP using function to get the largest number from Ans. # ilename: Ch-datas-p 010
a list using loop.
Ans. def maxlist( list ):
|FileName:ch-datas\Q22| def ZeroEnding (SCORES):
S=0
max = list[ 0 ] for i in SCORES:
for a in list: if 1%10- =0:
if a > max: S=S+i
max a print (s)
return max
lst=eval(input ("Enter the list")) 61. Write definition of aMethod COUNTNOWPLACES)
print (maxlist (1st) ) to find and display those place names, in which there
are more than 5 characters.
58, Write a user defined function arrangelements(X),that
accepts a list X of integers and sets all the negative For example:
If the list PLACES contains
elements to the left and all positive elements to the
right of the list. "DELHI", "LONDON'", "PARIS", "NEW
[FileName:ch-datas\Q23|
YORK", "DUBAI"I
For example:
The following should get displayed
if L=|1,-2,3,4,-5,7] ,
LONDON
Then the output should be: -2,-5,3,4,7] NEW YORK
Ans. def arrangelements (X): Ans. #Filename: Ch-datas -P_011
L=len(X) def COUNTNOW(PLACES):
for i in range (L): for P in PLACES:
if X[i]<0 and i! -0:
if len(P)>5:
j=i print (P)
while j! =0 and X[j-1]>0:
x[j],x[j-1]=X[j-1] ,x[i) 62. Write definition of a method OddSum(NUMBERS)
to add those values in the list of NUMBERS, which
j-j-1
are odd.
print (X)
Ans. #Filename : Ch-datas -P_013
59. Write the definition of a function Reverse(X) in
Python, to display the elements in reverse order def OddSun (NUMBERS):
the
such that each displayed element the twice of n=len(NUMBERS)
original element (element * 2) of the List X in the S=0

following manner: for i in range(n):


if (1%2! =0):
Example: S=s+NUMBERS[1]
If List X contains 7 integers is as follows:
print(s)
X[1| X[2] X(3) X|4) X[5] XJ6]
5 6 2 10 63. WAP in python to create the duplicate copy of the
4
list.
After executing the function, the array content should Ans, #Filename:Ch-datas -P_014
be displayed as follows: original [10, 22, 44, 23, 4]
Ans, #Filenane:Ch-datas-P_09 newlist list(original)
def Reverse(X): print (original)
for i in range (lern (%) -1, -1, -1): print (newlist)
print (%1i] *2)
6). Write definition of a method ZeroEnding(SCORES) 64. Write a Python program to print the numbers of a
to add all those alues in the list of SCORES, which specified list after removing even numbers from it.
areending with zero (0) and display the sum. Ans. #Fi lenane:Ch datas-P 015
[7,8, 120, 25, 4lo, 20, 27)
For example,
num x for x in num if x%2! 0
If the SCORES contain (200,456,300,100,234,678)
print(num)
The sum should be displayed as 600,
78 7agetker utk Computer Science (Python)-12
3 things:
The program should do
65. Write definition of aMethod AFIND(CITIES) to random numbers
display all the city names from a list of CITIES, () Should create the list of 5
between 10 to 99.
which are starting with alphabet A. random numbers
For example: () Should create the tuple of 5
between 10 to 99.
If the list CITIES contains keys:values
|"AHMEDABAD". "CHENNAI", "NEW (iüi) Should create the dictionary of 5
its value.
random characters as key and ASCIl as
DELHI", "AMRITSAR", "AGRA"]
import random
Ans.
The following should get displayed def createTuple():
AHEMDABAD
a-()
AMRITSAR for i in range(5):
AGRA n=random. randint(10,99)
Ans, #Filename: Ch-datas -P_Q16 a+=(n,)
return a
def AFIND(CITIES):
for i in CITIES: def createlList():
if i[o]=='A': a=[]
print (i) for i in range(5):
n=random. randint(10,99)
Long Answer a+=[n]
Type Questions 5 Marks return a

def createDict():
66. Write a python program using functions to do the
following task: a-{)
(a) To check whether the entered number is prime for i in range(5):
X=random. randint(65,90)
or not.
X=chr(x)
(b) To print all the prime number between the 2 to n.
n=random. randint(10,99)
Also write the python statements to execute these
Filename:ch3_Q10 a. update({x:n})
function.
Ieturn a
Ans. def isPrine (n):
#A number is prine if it is not divisible by
any number tpl=createTuple ()
from 2 to its square root print ("Tuple:",tpl)
p=True lst=createList()
d=2 print ("List",lst)
while d<=pow(n,0.5) and p: dict=createDict()
if n%d==0: print("Dictionary: ",dict)
p=false
else: d+=1 68. Write apython program using function to find greater
return p number between two numbers. The function should
def showPrime(n): take 2 numbers as parameters.
print("Prime numbers in the range 1 Filename: ch-3 Q12
to",n, "are: ")
for i in range(2, n+1):
Ans. def Greater (n1,n2) :
if n1>n2:
if isPrime (i) : #Calling isPrine () from
showPrine () print (n1,"is qreater")
prínt (i,end=" ") elif n2>n1:
print("To dísplay prine numbers from 1 to n:") print (n2,"is greater")
n=int(input("Enter the value of n: ")) else:
showPrine (n) print("numbers are equal")
67, Write a python program using function to demonstrate n1 eval(input("'Enter a number: )
)
random0) along with list, tuple and dictionary. n2 eval(input('EnteI another nunber:

Filename: ch-3_Q11 Greater (nl, n2)


Functions 79
69. Write a python program using function to print the Vol=Pi*r*r*h/3
sum of first n natural numbers. print("Total Surface Area
Filename: ch-3_Q13 ,rOund(TSA, 2), "sq. units")
ÀNS. def l0opl (n): print ("Volume =", rOund (Vol,2),
Sum=0 "cu. units")
i = 1 else: print("Invalid choice")
while i<-n: print ("1. Cylinder")
Sum += i print ("2. Sphere")
i +: 1 print("3. Cone")
print (" sum of first",n, "natural numbers Pi=3.14

=", sum) choice-eval(input ("Enter your choice (1, 2, or 3): "))


X= int(input("Enter the value of x: ")) calculate (choice)
loop1(x) 72. Write python program using function to find the sum
of first n terms of the following series:
70. Write a python program using function to print
the table of the number. The function should take a X -x²+ x
numbers as parameter. Filename: ch-3_Q14 where n and x have to be input from the user. The
Ans. def loop2 (n): function should have two parameter n and x and
i-1 return the sum of the series. Filename: ch-3 Q16
while i<=10:
Ans. "Program 16'' '
print (n,"x",i,"=",n*i) def sumseries (x, n):
i+=1
sum=0
x = eval(input ("Enter a nunber: ")) for i in range (1, n+1):
loop2(x) if i%2==1: sum += pow(x,i)
71. Write a menu based python program using function else: sum -= pow(x,i)
return sum
to find TSA and Vol of Cylinder, Sphere and Cone
according to choice entered by the user. n=eval(input ("How many terms? "))
n=abs(int (n) )
Filename: ch-3_Q15 X=eval(input ("Enter the value of x: "))
Ans. def calculate (choice): print("Sum of first", n, "terms of the series
if (choice=-1) : ',sumseries (x, n))
I=eval(input ("Enter radius of cylinder: ")) 73. Write python program using function tofind the sum
h=eval(input ("Enter height of cylinder: "))
of first n terms of the following series:
TSA=2*Pi*r*h+Pi*r*I
Vol=Pi*r*r*h 1 -x+
print("Total Surface Area
=",rOund(TSA, 2),"sq. units") where n and x have to be input from the user. The
print("Volume =", round (Vol,2), "cu. function should have two parameter nand x and
units") return the sum of the series. Filename: ch-3_Q17
elif (choice==2) : Ans. 'Program sumseries'
r=eval(input ("Enter radius of sphere: ")) def sumseries (x,n):
TSA=4*Pi*r*r sum=1
Vol=4*pi*r*r*r/3 factorial-1;
print("Tota l Surface AIea or i in range (1,n):
=",rOund(TSA, 2), "sq. units") factorial*=i
print("Volume = .round (Vol,2), "cu. sum += pow((-x),i)/factorial
units") Ieturn sum
elif (choice= =3) : n=eval(input ("How many terms? "))
I=eval(input ("Enter radius of cone:")) n=abs (int (n))
h=eval(input ("Enter height of cone: ")) X=eval(input("Enter the value of X: "))
1 (r*r+h*h)**0.5 print("Sum of first",n, "terms of the series
TSA=Pi*r*l+Pi*r*r ",sumseries (x, n))
80 Together eek Computer Science (Python)-12
P=P/0
accept a
74. Write a python program using functionoftoall the list 0=P%0
list as parameter and return the sum print (P, "#",0)
elements.
Filename: ch-3_Q18 Ieturn P
elements
Ans. 'Program to print the sum of all the A=200
using fucntion''"
B=20
def sumlist(lst): A=changer (A, B)
Sum=0 print(A, "$",B)
for i in range (0, len(1st) ): B=changer (B)
sum+=lst[i]
return sum
print (A, "$", B)
10.0 # 10.0
lstl=eval (input("Enter the list")) Ans.
print (lst1) 10.0 S 20
(lst1))
print ("Sum of the list is ", sumlist 2.0 # 2.0
function to accept a 10.0 $ 2.0
75. Write a python program using following code?
print all the even number in 79. #What is the output of the
list as parameter and Filename: ch-3 Q19
the list. a=10
elements using
Ans. 'Program to print the even b-20
fucntion ' def change():
def displaylist(lst): global b
print("Even Elemnets of the list") a=45
for i in range (0, len (lst) ): b=56
if lst[i]%2==0: change()
print (1st[i]) print(a)
lstl=eval (input("Enter the list")) print (b)
displaylist (1st1) 10
Ans.
using function to accept a
76. Write a python program allthe odd elements by
56
list as parameter and multiply
demonstrate by reference 80. WAF to find the power of
a number.
5. [This program will also
concept]
Filename: ch-3_Q20 Ans. def power(X, y=2) :
using function to I = 1
'Write a python program for i in range(y):
Áns. and multiply all
accept a list as parameteI will also
5.[This program I I X
the odd elements by concept]'"
demonstrate by reference return r

def displaylist (1st): print (power(3))


for i in range(0, len(1st) ): print (power (3, 3) )
if lst[ij%2==1:
lst[i]=lst[i]*5 Output
9
print("New List in function call", lst)
27
lst=eval (input ("Enter the list")) EvenSum(NUMBERS)
print("List before the function
call",lst) 81. Write definition of a function NUMBERS, which
displaylist (lst) to add those values in the list of
print("List after the function
call", lst) are odd on position. |FileName:ch-datas\Q34|
program:
77. Write the output of the given Ans. def EvenSum (NUMBERS):
def displaylist (1st): n=len (NUMBERS)
:
for i in range(0, len(1st) ) s=0
if lst[i J%2--1: for i in range(n):
lst[i]-lst[i] *5
if (i%2!=0):
lst=[23, 12, 34,45, 67] S=s+NUMBERSIi]
displaylist (1st)
print(s)
double theeven
print("List", 1st)
34, 225, 3351 82. Write the function Change), to presentina
Áns, List [115, 12,
following code elements and triple the odd elementsparameter:
78. Find theoutput of the list. The function will take and list as
P=100 also return the list.
def changer(P, 0-10):
Functions 81
Ans. def change (L): 86. WAF to takea list and inserting element as parameter
A-[] and insert the new element at begining of the list.
for i in L: Ans. def insertbeg(list,n):
if i%2==0: # Inserting n in the list
A.append(i*2) list = [n] list[o:]
else: print("New List", list)
# Main
A. append(i*3)
return A li=eval(input ("Enter the List"))
ele=int(input ("Enter the new element to be
83. Write a Function Filter) which will take a list as inserted"))
parameter and made the different lists Even|| and insertbeg (li, ele)
Odd|]. And then combine the two list and return the 87, WAP using function to change the alternate index
main list i.e. nested list. value of the element.

Ans, def filter(L): Input:


(1,2,3,4,5)
even=[] Output:
odd=[] [2,1,4,3, 5]
master=[] Ans. def alternate (1):
for i in L: for i in range(1en(1) -1) :
if i%2==0:
if i%2-=0:
1[1],1[i+1]-1[i+1], 1[i]
even.append(i) return 1
else: #Main
odd. append (i) l=eval(input ("Enter the list"))
master.append (even) ans=alternate(1) # Calling of function
master.append (odd) print ("New list =",ans)
return master 88. Write a Python Function to count the number of
elements in a list within a specified range.
84. Write a function Common ) to accept lists as #Assuming that list is in sorted order.
argument and return the list with common elements 'input = [1,2,5,6, 8, 9,10, 15, 19, 20,25]
from both the lists. 5
20
Ans. def comnon(L1, L2):
8

for i in L1:
Ans. def countl(li, ml,m2):
if i in L2: ctr = 0
C. append(i) for x in range(len(li) ):
return c if m1 <= lilx] <= m2:
ctr += 1
85. WAP using function to insert new element in sorted
return ctr
list.
li-eval(input ("Enter the list"))
def insertnew(1ist, n):
m1=int (input("Enter the first limit"))
for i in range(1len (list) ): m2-int (input ("Enter the second linit"))
if list[i] > n: ans=countl(li, m1, m2) # Calling of function
index =i print("Total countt =",ans)
break
89, Write a Python program to push all zeros to the end
# Inserting n in the list of a given list a. The order of the elements should
list = list [ :1] + [n] + list[i:) not change.
print("New List", list) Input: Elements of the list with each element
# Main separated by a space.
Output: Elements of the modified list wìth each
li-eval(input ("Enter the List in ascending element separated by a space. After the last
order") ) element, there should not be any space.
ele=int(input("Enter the new element to be Example:
inserted")) Input:0 2 3 4 67 0 1
insertnew(1i, ele) Output:2 3 4 67 1 0 0
82 Together wcek Computer Science (Python)-12
cOunt +: 1
Ans. def pushZerosToEnd(arr, n):
#Main
9)
arr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0,
count
for i in range(n): n = len(arr)
if arr[i] ! 0: pushZerosTo End (arr, n)
arr[count] = arr[i] end of
count+=1 print( "Array after pushing all zeros t0
while count < n:
array:")
print(arr)
arr[count] = 0

PRACTICE QUESTION, BANK


(c) from module name import function _namne
Objective Type (All of the above
Questions 1Mark 8. What is the syntax for calling a function in a
module?

1. In what order is code executed in afunction? (a) function name()


(aYFrom the top of the function to the bottom f6 module name. function name(0
(b) From the bottom of the function to the top (c) import module name
(c) It depends on the type of function (d) None of the above
(d) None of the above 9. What the syntax for creating a function with no
parameters or return value?
2. What is the scope of avariable defined inside a function?
Aa) def function name():
(a) Global scope
6) Local scope (b) def function_name(paramneter):
(c) Both global and local scope (c) def function name() -> return:
(d) Static Scope (d) def function name() -> parameter:
3. What is the scope of a variable defined outside of any 10. What is the syntax for creating a function with a single
function? parameter and no return value?
(a) Global scope (a) def function_name):
(b) Local scope t5) def function_name(parameter):
(c) Both global and local scope
(c) def function name() -> return:
(d) None of the above
(a) def function_name() -> parameter:
4. What keyword is used to define a variable in the global. 1. What is the syntax for creating a function with multiple
scope? parameters and a return value?
(a) local (6 global
(c) scope (d) var (a) def function name():
(b) def function name(paranmeter):
5. Which of the following is not a built-in function in
Python? (e) def function name(parameterl, parameter2)
6 len(0 return:
(a) print() parameter2) >
(d) random() (d) def function name(parameterl,
(c) input() parameter3:
6. Which module in Python provides mathematical
funçtions? 12. What is the output of the following funetion?
(á) math (b) random def add numbers(a, (b):
(c) os (d) sys return a + b
7. What is the syntax for importing a module in Python? print(add numbers(5, 10))
(a) import module name 15 (b) 10
(b) from module name import the above
(c) 5 (d) None of
Functions 83
13. What is the output of the following function? 19. Assertion (A): A function defined in a module can be
def print name(name): used in another module in Python.
print("My name is " + name) Reason (R): This requires the module containing the
function to be imported using the import statement.
print_name("Alice") 20. Assertion (A): A function in Python can have only one
ta) My name is Alice return statement.
(b) Alice Reason (R): (a) This ensures that the function always
(c) NameError: name 'name' is not defined returns a value.
(d) None of the above 6) Havingmultiple return statemnents can
lead to confusion and errors.
14. What is the output of the following function?
21. Assertion (A): Afunction in Python can be defined
def add_numbers(a=0, b-0): inside another function.
return a+b Reason (R): (d) This is known as nested function or
inner function.
print(add numbers()) (b) The nested function can access variables
print(add numbers(S) from the outer function.
print(add numbers(5, 10)) 22. Assertion (A): Afunction in Python can modify the value
fá) 0 5 15 (b) 00 0 of a global variable without using the global keyword.
(c) 55 15 Reason (R): (a) This is a recommended practice to
(d) None of the above avoid name clashes.
15. If a function doesn't have a return statement, which of ( This can lead to unexpected behavior
the following does the function return? and bugs.
(a) int Short Answer
(b) null
Type Questions 2/3 Marks
LeyNone
(d) Anexception is thrown without the return statement 23. Write the purpose of def keyword.
16. What will be the output of the following Python code? 24. Write few examples of Built in python function.
|CBSE 2021] 25. Write the function header(declaration) which consist
of two parameter one is X and other one is y with its
def FunStr(S): default value "hi".
J=""
26. Define Scope.
for i in S:
27. Write functions in Python for PushS(List) and for
If i.isdigit(): PopS(List) for performing Push and Pop operations
T=T + i with a stack of List containing integers.
return T CBSE 2021 (C))
X = "PYTHON 3.9"
28. What is default argument? Explain with help of an
Y=FunStr(X) example.
print (X, Y, sep="*") 29. Rewrite the following python code after removing any/
Say PYTHON 3.9 (b) PYTHON 3.9*3.9 all syntactical errors with cach correction underlined:
(c) PYTHON 3.9*39 (d) Error Def displaylist (lst):
17. What will be the output of the following Python code? print("Even Elements of the list")
|CBSE 2021| for i in Range(0, len(lst)):
if lst[iJ%2-0:
V = 50
print(lst[i))
def Change (N): lstl=eval(input ("Enter the list"))
global V displaylist()
V, N N, V 30. Write the output of the given program:
print(V, N, sep="#", end="@") def displaylist(1st):
Change (20) print("Even Elements of the list")
print (V) for i in range(0, len(lst)):
ao 20450020 if lst{i ]*2=0:
(b) 50020#50 print(lst[i})
(c) 50#50#50 (d) 20¢50#20 st1-(23,45, 12, 10,16, 17]
18. What is function calling? di splaylist(lsti)
84 agetkcr avk Computer Scicnce (Python)-12
31. Write the output of the given program: 37. Find the output
def loopl(n): def show(a, b) :
sum=0 return a+b
print("Addition is : ", show("679," "str")
while i<=n:
38. Find the output
Sum + i def Check (K, L=70):
i +* 5
if (K>L):
print ("sum =",sum) K-=L
X = 30 else:
loop1(x) K+=L
32. Write the output of the given program: M=100
def display (n): N=40
sum=5 Check (M, N)
i = 1 print(M, "#",N)
while i<-n: Check (M)
SUm += i print (N, "#", M)
i += 5 39. What will be the scope of the variables a, b, c, d, e?
Sum=sum-2 def show():
print ("Value =", sum," i= ",i) a=10
X 30 b=15
display (x) c=30
33. Rewrite the following code in python after removing all def show1() :
X="Together With"
syntax error(s). Underline each correction done in the
code. y=100
def Sum(Count) #Method to find sum z=10
S=0
for I in Range(1, Count+1): Long Answer
S+-I Type Questions 5 Marks
RETURN S
print (Sum[2]) #Function Call 40. Write a python program using function to check whether
print (SUM[5]) a number is Armistrong or not. The function will accept
34. Write the output of the given python program: a number as parameter.
(a) def Sum(Count): #Method to find sum 41. Write a menu driven python program using function
S=0 to do the following: 1. Reverse a Number, 2. Check
for I in range(1, Count+1): whethera number is Palindrome or not and3. To check
S+=I
return S whether it is Armstrong or not and 4 to exit. Program
print (Sum(2)) #Function Call should continue till the user says 'no'.
print (Sum(5)) 42. Write a python program using function to accept the list
(b) for í in range(-10, -100, -30): as parameter and print the odd element of the list.
print(i) 43. Write a python program to accept the list as parameter
(c) X=7 and print the prime numbers of the list.
def new_value():
X=70
44. Write python program using function to find the sum of
print("x=", x) first n terms of the following series:
print("x=", x)) 1+ x + t...
newvalue()
print("xe",x) where n and x have to be input from the user. Ine
35. Write a function, on calling it willcalculate the factorial function should have two parameter n and x and returt
of the integer passed as a parameter, and return this the sum of the series.
factorial. The function will not display anything but 45. Write python program using function to find the sunm
will simply return the calculated result. first n terms of the following series:
Filename: ch-3 Q8 7
+
36, Write apython function to print the number of the digits 3! S! 7! user. The
in number. The function digil) will take the number as where n and x have to be input from the and retum
parameter and the number of digits one, two, three or function should have two parameter n and x
more than three digits. Filename: ch-3 (Q9 the sum of the series.

Answers to all unsolved questions are given at the


end of all the chapters

You might also like