Functions
Functions
Question 1:
What is sys.argv?
Answer:
A list containing the program name and all the command-line arguments to a
program.
Question 2:
What can you do with the eval function?
Answer:
Eval(s) evaluates an expression contained in a string s and returns the resulting
object.
o m
Question 3:
.c
What does sys.argv[1:] mean?
Answer:
er
Question 4:
uf
What type of errors does the exception type NameError correspond to?
Answer:
Ed
Question 5:
Why we use ceil(x) function?
Answer:
It returns the ceiling of x as a float, the smallest integer value greater than or
equal to x.
Question 6:
Why we use floor(x) function?
Answer:
It returns the floor of x as a float, the largest integer value less than or equal to x.
https://www.edufever.com/
Question 7:
Explain fabs(x) in python?
Answer:
It returns the absolute value of x.
Question 8:
What value will be return by exp(x) ?
Answer:
Returns e**x.
Question 9:
What value will be return by log10(x) ?
Answer:
Returns the base-10 logarithm of x. This is usually more accurate than log(x,10).
m
Question 10:
What value will be return by sqrt(x)?
o
.c
Answer:
Returns the square root of x.
er
Question 11:
ev
Answer:
Returns the cosine of x radians.
Ed
Question 12:
Write the output of sin(O)?
Answer:
Returns the zero.
Question 13:
Define tan(x) function in python.
Answer:
Tan(x) function return the tangent of x radians.
Question 14:
Why we use degrees(x) ?
Answer:
It converts angle x from radians to degrees.
https://www.edufever.com/
Question 15:
What is the advantage of radians(x) ?
Answer:
It converts angle x from degrees to radians.
Question 16:
What value will be return by random() ?
Answer:
Return the next random floating point number in the range (0.0,1.0).
Question 17:
“A module cannot contain a main program”. Is this statement true?
Answer:
False
m
Question 18:
o
What gets printed? Assuming python version 2.x print type(l/2)
.c
Answer:
<type’int’>
er
Question 19:
ev
Answer:
< type’list’>
Ed
Question 20:
What is the output of the following code? def f(): pass print type(f())
Answer:
<type’NoneType’>
Question 21:
What should the below code print?
print type(1J)
Answer:
< type’complex’>
Question 22:
What will be the output of the following code
https://www.edufever.com/
class c (object):
….def_init_(self):
self.x = 1
C = C()
print C.X
print C.X
print C.X
print C.X
Answer:
All the outputs will be 1, since the value of the objects attribute (X) is never
changed.
1
1
m
1
1
o
.c
X is now a part of the public members of the class C. Thus it can be accessed
directly.
er
ev
Question 23:
What gets printed with the following code ?
uf
d= lambda p: p * 2
Ed
t = lambda p: p * 3
x=2
x = d(x)
x = t(x)
x = d(x)
print x
Answer:
24
Question 24:
What gets printed with the following code ?
https://www.edufever.com/
x = 4.5
y=2
print x//y
Answer:
2.0
Question 25:
What gets printed with the following code ?
print “hello” ‘world’
Answer:
On one line the text: helloworld
Question 26:
m
What gets printed by the code snippet below?
import math
print math.floor(5.5) o
.c
Answer:
er
5.0
ev
Question 27:
What gets printed by the code snippet below?
uf
x = “foo ”
Ed
y=2
print x + y
Answer:
An exception is thrown.
Question 28:
What does the following code do?
def a(b, c, d): pass
Answer:
It defines a function, which does nothing.
Question 29:
What do you mean by function?
Answer:
https://www.edufever.com/
A function is a block of organized, reusable code that is used to perform a single,
related action.
Question 30:
Do Python supports built-in functions?
Answer:
Yes, Python gives you many built-in functions like print() etc.
Question 31:
Can First statement of a function be optional?
Answer:
Yes, The first statement of a function can be an optional statement.
Question 32:
Why we use return [expression] in Python?
m
Answer:
o
The statement return [expression] exits a function.
.c
Question 33:
er
Write syntax for function that takes a string as input parameter and prints it on
standard screen.
ev
Answer:
uf
print str
return
Question 34:
Why do we define a function?
Answer:
Question 35:
When we can execute a function?
Answer:
Once the basic structure of a function is finalized, we can execute it
https://www.edufever.com/
Question 36:
Are all parameters (arguments) in the Python language passed by reference.
Answer:
Yes,All parameters (arguments) in the Python language are passed by reference.
Question 37:
How do we define a function ?
Answer:
Here are simple rules to define a function in Python.
● Function blocks begin with the keyword def followed by the function name and
Parentheses ()
● Any input parameters or arguments should be placed within these parentheses.
● The first statement of a function can be an optional statement – the
documentation string of the function or docstaing.
m
● he code block within every function start with color(:) and is indented.
o
● The statement return [expression] exits a function, optionally passing back an
.c
expression to the caller. A return statement with no arguments is the same as
return none.
er
ev
Question 38:
What are the various types of para-meters ?
uf
Answer:
Ed
Question 39:
What are Required arguments?
Answer:
Required arguments are the arguments passed to a function in correct positional
order.
Question 40:
Explain default argument.
Answer:
https://www.edufever.com/
A default argument is an argument that assumes a default value, if a value is not
provided in the function call.
Question 41:
Write the syntax of lambda functions?
Answer:
The syntax of lambda functions contains only a single statement, which is as
follows:
lambda[arg1 [,arg2, argn]] :expression
Question 42:
What is the use of lambda keyword in Python?
Answer:
You can use the lambda keyword to create small anonymous functions.
m
Question 43:
Explain return keyword.
o
.c
Answer:
The statement return [expression] exits a function, optionally passing back an
er
expression to the caller.
ev
Question 44:
uf
The scope of a variable determines the portion of the program where you can
access a particular identify.
Question 45:
What are two basic scopes of variables in Python?
Answer:
Global variables and Local variables.
Question 46:
What does the following code do? def simpleFunction():
“This is a cool simple function that returns 1”
return 1
print simpleFunction._doc_[10:14]
Answer:
cool
https://www.edufever.com/
Question 47:
Which variables have local scope?
Answer:
Variables that are defined inside a function body have a local scope.
Question 48:
Which variables have global scope?
Answer:
Variables that are defined outside a function body have a global scope.
Question 1:
What is a Python module ? What is its significance ? .
Answer:
m
A ‘module’ is a chunk of python code that exists in its own (.pu) file and is
o
intended to be used by python code outside iteself. Modules allow one to fundle
.c
together code in a form in which it can easily be used later.
The modules can be ‘imported’ in other programs so the function and other
er
definitions in imported modules becomes availabe to code that imports them.
ev
Question 2:
uf
“Python has certain functions that you can readily use without having to write any
special code.” What type of functions are these ?
Ed
Answer:
The pre-defined functions that are always available for use are known as python’s
built-in functions. For example :
len (), type (), int (), raw-input () etc.
Question 3:
What is the utility of built-in function help () ?
Answer:
Python’s built in function help ( ) is very useful. When it is provided with a
program-name or a module-name or a function-name as an argument, it displays
the documentation of the argument as help. It also displays the docstrings within
its passed-argument’s definition. For example :
help (math)
will display the documentation related to module math.
https://www.edufever.com/
Question 4:
What is the utility of Python standard library’s math module and random module
?
Answer:
Math module is used for math related functions that work with all number types
except for complex numbers, radom module is used for different random number
generator functions.
Question 5:
What is raw_input?
Answer:
It is a function which takes a string (e.g., a question) as argument, writes the
string to the terminal window, halts the program and lets the user write in text on
the keyboard, and then the text is returned to the calling code as a string object.
m
Question 6:
What value will be return by log(x[, base])?
o
.c
Answer:
With one argument, return the natural logarithm of x (to base e).
er
With two arguments, return the logarithm of x to the given base, calculated as
ev
log(x) log(base)
uf
Question 7:
Define pow(x, y) function in Python ?
Ed
Answer:
Return x raised to the power y.. In particular, pow(1.0, x) and pow(x, 0.0) always
return 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative,
and y is not an integer then pow(x, y) is undefined, and raises ValueError.
Question 8:
Determine what is printed by the following program listinput.py,
list1 = eval(raw_input(‘Give a list:’))
list2 = eval(raw_input(‘Give another list:’))
print list1 + list2
When the program is running as follows:
Unix/DOS > python listinput.py
Give a list: ‘[1,2]’
Give another list: “[3,4]”
https://www.edufever.com/
Answer:
[1,2] [3,4]
Question 9:
What will be the output of this program?
a = 20.3
b = ‘Python’
c = ‘”Python”‘
d = 21
print isinstance(a, float),
print isinstance(b, (str, int)),
print isinstance(c, (str, str)),
print isinstance(d, (float, str))
Answer:
True, True, True, False.
om
Question 10:
.c
Write any Python expression which is a valid input argument to the following
program?
er
input = eval(raw_input(‘Value:’))
ev
‘one’
Ed
Question 11:
Given the program
from scitools.StringFunction import
StringFunction
import sys
formula = sys.argv[1]
f = StringFunction(formula)
print f(2)
Will this input work?
Unix/DOS > python function.py ‘t**2’
Answer:
No, This input will not work
https://www.edufever.com/
Question 12:
What will happen when you run the following program:
import sys
try:
t = sys.arg[1]
a = sys.arg[2]
except:
print ‘You must provide TWO
command-line arguments!!!’
sys.exit(1)
s = 0.5*a*t**2
print s
Answer:
The program will always respond with, “You must provide TWO command-line
m
arguments!!!”, regardless of what you write on the command line
Question 13:
o
.c
How can you make a module ‘helloworld’ out of these two functions?
er
def hello():
print ‘Hello,’,
ev
Answer:
Put the functions in a file with name helloworld.
Ed
py
Question 14:
Write a program to read the user name using raw_input() and display back on the
screen using print()
Answer:
#!/usr/bin/python
name=raw_input(‘Enter your name :’)
print (“Hi %s, Let us be friends!” % name);
Question 15:
What does the len() function do?
Answer:
https://www.edufever.com/
It gets the length of the string that you pass to it then returns it as a number. Play
with it.
Question 16:
How do you make a higher order function in Python ?
Answer:
● A high order function accepts one or more functions as input and returns a new
function. Sometimes it is required to use function as data.
● To make high order function, one need the import functools module.
● The functools.partial() function is used often for high order function.
Question 17:
What value will be return by “choice(seq)” ?
Answer:
m
A random item from a list, tuple, or string.
Question 18: o
.c
What value will be return by “random()” ?
er
Answer:
A random float r, such that 0 is less than or equal to r and r is less than 1.
ev
Question 19:
uf
Answer:
([l, 2, 3,5,9]): 2
choice(‘A String’) :n
https://www.edufever.com/
Question 20:
Give an example of “random()”
Answer:
The following example shows the usage of random() method.
# !/usr/bin/python
import random
# First random number
print “random(): ” ,
random.random() # Second random number print “random(): “,
random.random()
This will produce the following results
random(): 0.281954791393
random(): 0.309090465205
m
Question 21:
Describe trignometric functions ?
o
.c
Answer:
Python includes following functions that perform trignometric calculations.
er
ev
Function Description
Return the arc cosine of x, in
uf
acos(x)
radians.
Ed
https://www.edufever.com/
Converts angle x from radians
degrees(x)
to degrees.
Converts angle x from de-
radians(x)
grees to radians.
Question 22:
Describe random functions ?
Answer:
Random numbers are used for fames, simulations, testing, security, and privacy
applicatons. Python includes following functions that are commonly used.
Function Description
A random item from a list, tuple,
choice(seq)
m
or string.
randrange
([start,] stop
A randomly selected element
o
.c
from range(start, stop, step)
[,Step])
er
A random float, such that 0 is
ev
Question 23:
Write a program to swap two numbers.
Answer:
a=5
https://www.edufever.com/
b=9
def swap(c,d):
return d,c
swap(a,b)
Question 24:
What are the rules to define a function in Python?
Answer:
You can define functions to provide the required functionality. Here are simple
rules to define a function in Python:
(1) Function blocks begin with the keyword def followed by the function name
and parentheses (( ))
(2) Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
m
(3) The first statement of a function can be an optional statement-the
o
documentation string of the function or docstring.
.c
(4) The code block within every function starts with a colon (:) and is indented.
(5) The statement return [expression] exits a function, optionally passing back an
er
return None.
uf
Question 25:
Give an example for defining a function.
Ed
Answer:
def functionname(parameters):
“function_docstring” function_suite
return[expression]
Question 26:
Write a program to illustrate function call.
Answer:
#!/usr/bin/python # Function definition is here
def printme(str): “This prints a passed string into this function”
print tr;
return; # Now you can call printme function printme(“Mohd saif naqvi”);
printme(“Chairman of Waltons Technology”)
It produces following result:
https://www.edufever.com/
Mohd saif naqvi
Chairman of Waltons Technology
Question 27:
Write a program to illustrate “Pass by refe-rence vs value”
Answer:
#!/usr/bin/python # Function definition is here
def changeme(mylist): “This changes a passed list into this function”
mylist.append([l,2,3,4]);
print “Values inside the function: “, mylist
return # Now you can call changeme
function mylist=[10,20,30];
changeme(mylist);
print “Values outside the function: “, mylist
It produce following result:
m
Values inside the function: [10, 20,30, [1,2,3,4]]
o
Values outside the function: [10,20, 30, [1,2,3,4]]
.c
Question 28:
er
Answer:
uf
#!/usr/bin/python
# Function definition is here
Ed
def printme (str): “This prints a passed string into this function”
print str;
return;
# Now you can call printme function printme();
It produces following result:
Traceback (most recent call last):
File “test.py”, line 11, in <module>
printme()
TypeError: printme() takes exactly 1 argument (0 given)
Question 29:
Write a program to illustrate “Keyword arguments”.
Answer:
https://www.edufever.com/
#!/usr/bin/python
# Function definition is here
def printme(str):”Thisprints a passed string into this function”
print str;
return;
# Now you can call printme function
printme(str=”My string”);
When the above code is executed, it produces following result:
My string
Question 30:
Write a program to illustrate “default argument”.
Answer:
#!/usr/bin/python
m
# Function definition is here
def printinfo(name,age=35):
o
.c
“This prints a passed info into this function”
print “Name: “,
er
age return;
# Now you can call printinfo function
uf
printinfo(age=50,name=”miki”);
printinfo(name=”miki”);
Ed
Name: miki
Age 50
Name:miki
Age 35
Question 31:
Write a program to illustrate “variablelength arguments”.
Answer:
#!/usr/bin/python
# Function definition is here
def printinfo(argl,*vartuple):
https://www.edufever.com/
“This prints a variable passed arguments”
print “Output is:”
print argl for var in vartuple :
print var return;
# Now you can call printinfo function
printinfo(10); printinfo(70,60,50);
Output is:
10
Output is:
70
60
50
o m
Question 32: .c
Explain Global vs. Local variables.
Answer:
er
Variables that are defined inside a function body have a local scope, and those
ev
they are declared whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared
Ed
Question 33:
Explain anonymous functions.
Answer:
You can use the lambda keyword to create small anonymous functions. These
functions are called anonymous because they are not declared in the standard
manner by using the def keyword, lambda functions have their own local
namespace and cannot access variables other than those in their parameter list
and those in the global namespace.
Question 34:
Explain Scope of Variables.
Answer:
https://www.edufever.com/
All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python :
Question 35:
What do you mean by module ?
Answer:
A module allows you to logically organize your Python code. Grouping related
code into a module makes the code easier to understand and use. A module is a
Python object with arbitarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define
m
functions, classes, and variables. A module can also include runnable code.
o
.c
Question 36:
What do you mean by globals() and locals () Functions.
er
Answer:
ev
The globals( ) and locals( ) functions can be used to return-the names in the global
and local namespaces depending on the location from where they are called.
uf
If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.
Ed
If globals() is called from within a function, it will return all the names that can be
accessed globally from that function .The return type of both these functions is
dictionary. Therefore, names can be extracted using the keys() function
Question 37:
Explain reload)) Function.
Answer:
When the module is imported into a script, the code in the top-level portion of a
module is executed only once.Therefore, if you want to re-execute the top -level
code in a module, you can use the reload() function.
The reload() function imports a previously imported module again. The syntax of
the reload)) function is this :
reload (module_name)
https://www.edufever.com/
Question 38:
What are docstrings ? How are they useful ?
Answer:
A docstring is just a regular python triple- quoted string that is the first thing in a
function body or a module or a class. When executing a functionbody the
docstring does not do anything like comments, but Python stores it as part of the
function documen-tation. This documentation can later be displayed using help))
function. So even though docstrings appear like comments but these are different
from comments.
Question 39:
Find the error
def minus (total, decrement)
output = total – decrement
return output
m
Answer:
o
The function’s header has colon missing at the end.
.c
So add colon (:) at end of header line.
er
Thus, the correct code is
ev
return output
Ed
Question 40:
What would be the output produced by the following code:
import math
import random
print math=ceil (random.random)))
Answer:
The output would be :
1.0
random.random() would generate a number in the range [0.0, 1.0] but math.ceil (
) will return ceiling number for this range, which is 1.0 for all the numbers in this
range.
Thus the output produced will always be 1.0.
https://www.edufever.com/
Question 41:
Find the error(s) in the following code and correct them:
Answer:
Here, function name contains spaces. But function name should be a valid Python
identifier with no spaces in between. And here, no variable is defined to obtain
value being input. Lines 4 and 6 are badly indented; being part of same function,
m
those should be at the same indentation level as that of lines 2, 3, 5 and 7. And
o
also, variable favourite-game is an invalid identifier as it contains a hyphen, but it
.c
should have been an underscore.
er
Question 42:
ev
Answer:
https://www.edufever.com/
Question 43:
What would be the output of the follow-ing ? Explain. [CBSE Text Book]
def fl(): n = 44 def f2 (): n = 77
print “value of n”, n () print “value of n”, n
Answer:
value of n
Name Error : name ‘n’ is not defined.
Question 1:
Explain Comments in Python.
Answer:
Comments in Python :
A hash sign (#) that is not inside a string literal begins a comment. All characters
m
after the # and up to the physical line end are part of the comment, and the
Python interpreter ignores them.
o
.c
# !/usr/bin/python
er
# First comment
ev
print
“Hello, Python!”
uf
;
# second comment
Ed
https://www.edufever.com/
Question 43:
What would be the output of the follow-ing ? Explain. [CBSE Text Book]
def fl(): n = 44 def f2 (): n = 77
print “value of n”, n () print “value of n”, n
Answer:
value of n
Name Error : name ‘n’ is not defined.
Question 1:
Explain Comments in Python.
Answer:
Comments in Python :
A hash sign (#) that is not inside a string literal begins a comment. All characters
m
after the # and up to the physical line end are part of the comment, and the
Python interpreter ignores them.
o
.c
# !/usr/bin/python
er
# First comment
ev
print
“Hello, Python!”
uf
;
# second comment
Ed
https://www.edufever.com/
If we know before hand which functions, we will be needing, then we may use
‘from’. For modulus having large number of functions, it is recommended to use
‘from’ instead of import. Its syntax is
> > > from module name import function name 1 [, function name 2, ……….]
Example,
> > > from math import sqrt
> > > value = math . sqrt (36)
Question 4:
Explain ceil(x) in python.
Answer:
ceil(x)
Description : The method ceil( ) returns ceiling value of x-the smallest integer not
less than x.
Syntax:
m
Following is the syntax for ceil()
method import math
o
.c
math.ceil(x)
er
Note: This function is not accessible directly so we need to import math module
and then we need to call this function using math static object.
ev
Example:
Ed
# !/usr/bin/py thon
import math # This will import math module
print “math.ceil(-45.17):”,
math.ceil(-45.17)
print “math.ceil(100.12):”,
math.ceil(100.12)
print “math.ceil(100.72):”,
math.ceil(100.72)
print “math.ceil(119L):”,
math.ceil(119L)
print “math.ceil(math.pi):”,
math.ceil(math.pi),
This will produce the following result
math.ceil(-45.17) :-45.0
https://www.edufever.com/
If we know before hand which functions, we will be needing, then we may use
‘from’. For modulus having large number of functions, it is recommended to use
‘from’ instead of import. Its syntax is
> > > from module name import function name 1 [, function name 2, ……….]
Example,
> > > from math import sqrt
> > > value = math . sqrt (36)
Question 4:
Explain ceil(x) in python.
Answer:
ceil(x)
Description : The method ceil( ) returns ceiling value of x-the smallest integer not
less than x.
Syntax:
m
Following is the syntax for ceil()
method import math
o
.c
math.ceil(x)
er
Note: This function is not accessible directly so we need to import math module
and then we need to call this function using math static object.
ev
Example:
Ed
# !/usr/bin/py thon
import math # This will import math module
print “math.ceil(-45.17):”,
math.ceil(-45.17)
print “math.ceil(100.12):”,
math.ceil(100.12)
print “math.ceil(100.72):”,
math.ceil(100.72)
print “math.ceil(119L):”,
math.ceil(119L)
print “math.ceil(math.pi):”,
math.ceil(math.pi),
This will produce the following result
math.ceil(-45.17) :-45.0
https://www.edufever.com/
math.ceil(100.12): 101.0
math.ceil(100.72): 101.0
math.ceil(119L): 119.0
math.ceil(math.pi): 4.0
Question 5:
Explain exp(x) in python with example.
Answer:
Description : The method exp( ) returns exponential of x : ex.
Example:
Syntax: Following is the syntax for exp() method
import math
math.exp(x)
Note: This function is not accessible directly so w e need to import math module
and then we need to call this function using math static object.
m
Parameters : x—This is a numeric expression.
o
Return Value: This method returns exponential of x: ex.
.c
Example: The following example shows the usage of exp() method
er
# !/usr/bin/py thon
ev
math.exp(-45.17)
print “math.exp(100.12):”,
Ed
math.exp(100.12)
print “math.exp(100.72):”,
math.exp(100.72)
print “math.exp(119L):”,
math.exp(119L)
print “math.exp(math.pi):”,
math.exp(math.pi),
math.exp(-45.17): 2.41500621326e-20
math.exp(100.12): 3.03084361407e+43
math.exp(100.72): 5.52255713025e+43
https://www.edufever.com/
math.exp(119L): 4.7978133273e+51
math.exp(math.pi): 23.1406926328
Question 6:
Explain floor(x) in Python with example.
Answer:
The method floor() returns floor of x – the largest integer not greater than x.
Syntax: Following is the syntax for floor() method
import math
math.floor(x)
Note: This function is not accessible directly so we need to import math module
and then we need to call this function using math static object.
Parameters : x — This is a numeric expression.
Return Value: This method returns largest integer not greater than x.
Example: The following example shows the usage of floor() method.
o m
# !/usr/bin/python
.c
import math # This will import math module
print “math.floor(-45.17): “,
er
math.floor(-45.17)
ev
print “math.floor(100.12): “,
math.floor(100.12)
uf
print “math.floor(100.72): “,
math.floor(100.72)
Ed
print “math.floor(119L):”,
math.floor(119L)
print “math.floor(math.pi):”,
math.floor(math.pi)
math.floor(-45.17) :-46.0
math.floor(100.12): 100.0
math.floor(100.72): 100.0
math.floor(119L): 119.0
math.floor(math.pi): 3.0
https://www.edufever.com/
Question 7:
Explain log(x) in Python with example.
Answer:
Description : The method log( ) returns natural logarithm of x, for x > 0.
Syntax : Following is the syntax for log() method
import math
math.log(x)
Note: This function is not accessible directly so we need to import math module
and then we need to call this function using math static object.
Parameters : x — This is a numeric expression.
Return Value: This method returns natural logarithm of x, for x > 0.
Example: The following example shows the usage of log() method.
# !/usr/bin/python
import math # This will import
m
math module
print “math.log(100.12): ” ,
o
.c
math.log(100.12)
er
print “math.log(100.72): “,
math.log(100.72)
ev
print “math.log(119L):”,
math.log(119L)
uf
print “math.log(math.pi):”,
Ed
math.log(math.pi)
math.log(100.12): 4.60636946656
math.log(100.72): 4.61234438974
math.log(119L): 4.77912349311
math.log(math.pi): 1.14472988585
Question 8:
Explain loglO(x) in Python with example.
Answer:
Description: The method logl0() returns base -10 logarithm of x for x > 0.
Syntax: Following is the syntax for logl0() method
import math
https://www.edufever.com/
math.log10(x)
Note: This function is not accessible directly so we need to import math module
and then we need to call this function using math static object.
Parameters : x — This is a numeric expression.
Return Value : This method returns base -10 logarithm of x for x > 0.
Example: The following example shows the usage of log10() method.
# !/usr/bin/python
import math # This will import math module
print “math.logl0(100.12): “,
math.logl0(100.12)
print “math.logl0(100.72):”,
math.logl0(100.72)
print “math.loglO(119L):”,
math.log10(119L)
m
print “math.loglO(math.pi):”,
math.log10(math.pi)
o
.c
This will produce the following result:
er
ev
math.logl0(100.12): 2.00052084094
math.logl0(100.72): 2.0031157171
uf
math.log10(119L): 2.07554696139
math.loglO(math.pi): 0.497149872694
Ed
Question 9:
Explain pow(x, y) in python with example.
Answer:
Description : The method pow() returns returns
the value of x to the power of y.
Syntax: Following is the syntax for pow() method
import math
math.pow(x,y)
Note : This function is not accessible directly so we need to import math module
and then we need to call this function using math static object.
Parameters : x—This is a numeric expression, y—This is also a numeric
expression.
https://www.edufever.com/
Return Value : This method returns value of x to the power of y.
Example: The following example shows the usage of pow() method.
# !/usr/bin/python
import math # This will import math module
print “math.pow(100, 2): “,
math.pow(100,2)
print “math.pow(100,-2): “,
math.pow(100,-2)
print “math.pow(2,4): “,
math.pow(2,4)
print “math.pow(3, 0): “,
math.pow(3,0)
o m
math.pow(100, 2) :10000.0 .c
math.pow(100,-2): O.OOOl
math.pow(2, 4): 16.0 math.pow(3,0): 1.0
er
Question 10:
ev
Answer:
Description : The method sqrt( ) returns the square root of x for x > 0.
Ed
# !/usr/bin/python
import math # This will import math module
print “math.sqrt(100): “, math.sqrt(100)
print “math.sqrt(7): “, math.sqrt(7)
print “math.sqrt(math.pi): “, math.sqrt(math.pi)
https://www.edufever.com/
This will produce the following result:
math.sqrt(100): 10.0
math.sqrt(7): 2.64575131106
math.sqrt(math.pi): 1.77245385091
Question 11:
Describe Random numbers function in Python with example.
Answer:
Description : The method random( ) returns a random float r, such that 0 is less
than or equal to r and r is less than 1.
Syntax: Following is the syntax for
random() method
random()
Note : This function is not accessible directly so we need to import random
m
module and then we need to call this function using random static object.
Parameters: NA
o
.c
Return Value : This method returns a random float r, such that 0 is less than or
equal to r and r is less than 1.
er
#!/usr/bin/python
uf
random(): 0.281954791393
random(): 0.309090465205
Question 12:
Explain cos() in Python.
Answer:
Description: The method cos() returns the cosine of x radi Answer:
Syntax : Following is the syntax for cos() method
cos(x)
https://www.edufever.com/
Note: This function is not accessible directly so we need to import math module
and then we need to call this function using math static object.
Parameters : x—This must be a numeric value.
Return Value : This method returns a numeric value between-1 and 1 which
represents the cosine of the angle.
Example: The following example shows the usage of cos() method
# !/usr/bin/python
import math
print “cos(3):”,
math.cos(3)
print “cos(-3):”,
math.cos(-3)
print “cos(0):”,
math.cos(0)
m
print “cos(math.pi):”,
math.cos(math.pi)
o
.c
print “cos(2*math.pi):”,
er
math.cos(2*math.pi)
ev
cos(3) >0.9899924966
cos(-3) >0.9899924966
Ed
cos(0): 1.0
cos(math.pi) >1.0
cos(2*math.pi): 1.0
Question 13:
What are Generator Functions ?
Answer:
A generator function or generator method is one which contains a yield
expression. When a generator function is called it returns an iterator. Values are
extracted from the iterator one at a time by calling its_next_( ) method. At each
call to_next_( ) the generator function’s yield expression’s value (None if none is
specified) is returned. If the generator function finishes or executes return a Stop
Iteration exception is raised.
Generators provide an elegant way to write simple and efficient code for
https://www.edufever.com/
functions that return a list of elements. Based on the yield directive, they allow
you to pause a function and return an intermediate result. The function saves its
execution context and can be resumed later if necessary.
Question 14:
Define functions with example.
Answer:
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provides better modularity for your application and a
high degree of code reusing.As you already know, Python gives you many built-in
functions like
print( ) etc. but you can also create your own functions. These functions are called
user – defined functions.
Syntax:
def functionname(parameters):
m
“function_docstring”
function_suite return[expression]
o
.c
By default, parameters have a positional behavior, and you need to inform them
er
in the same order that they were defined.
Example:
ev
Here is the simplest form of a Python function. This function takes a string as
input parameter and prints it on standard screen.
uf
def printme(str):
Ed
Question 15:
Define functions calling with example.
Answer:
Defining a function only gives it a specific name, specifies the parameters that are
to be included in the function, and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
from another function or directly from the Python prompt. Following is the
example to call printme( ) function:
# !/usr/bin/py thon
# Function definition
https://www.edufever.com/
def printme(str):
“This prints a passed string into this function”
print str;
return;
# Now you can call printme function
printme (“I’m first call to user defined function!”);
printme (“Again second call to the same function”);
Question 16:
How are arguments passed – by reference or by value ?
m
Answer:
o
In Python everything is an object and all variables hold references to objects. The
.c
values of these references are to the functions. As a result you can not change the
value of the reference but you can modify the object if it is mutable. Remember,
er
numbers, strings and tuples are immutable, list and diets are mutable.
ev
Question 17:
uf
How can we pass optional or keyword parameters from one function to another
in Python ?
Ed
Answer:
Gather the arguments using the * and ** specifiers in the function’s parameter
list. It gives us positional arguments as a tuple and the keyword arguments as a
dictionary. Then we can pass these arguments while calling another function by
using
# and **
def funl (a, *tup, ** keyword.Arg):
keyword Argj’width’j = ‘23.3c’
fun2 (a, *tup, **keywordArg)
Question 18:
How to generate random numbers in Python ?
Answer:
The standard module random implements a radom number generator. *’
https://www.edufever.com/
There are also many other in this module, such as :
uniform(a, b) returns a floating point number in the range [a, b].
randint(a, b) returns a random integer number in the range [a, bj.
random() returns a floating point number in the range [0,1].
Following code snippet show usage of all the different functions, evertime it is
executed.
import random
i = random.randint (1, 99) # i randomly initialized by integer between range 1 and
99.
j = random randient (1,99) # j randomly initialized by float between range 1 and
99.
k = random.random() # k randomly initialized by float between range 0 and 1
Print (“i.”, i)
Print (“j.”,j)
m
Print (“k.”, k)
_______________
o
.c
Output:
er
(‘i:’, 64)
(‘j:’ 701.85008797642115)
ev
(‘k:’: 0.18173593240301023)
Output:
uf
(‘i:’,83)
Ed
(‘j:’,56.817584548210945)
(‘k:’; 0.9946957743038618)
Question 19:
Explain “The returnStatement” with example.
Answer:
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
All the above examples are not returning any value, but if you like you can return
a value from a function as follows :
#!/usr/bin/py thon
# Function definition is here
def sum(arg1,arg2):
https://www.edufever.com/
# Add both the parameters and return them.
” total=arg1+arg2
print “Inside the function : “,
total
return total;
# Now you can call sum function total=sum(10,20);
print “Outside the function total
Question 20:
Explain Namespaces and Scoping.
m
Answer:
o
Variables are names (identifiers) that map to objects. A namespace is a dictionary
.c
of variable names (keys) and their corres-ponding objects (values).
A Python statement can access variables in a local namespace and in the global
er
namespace. If a local and a global variable have the same name, the local variable
ev
shadows the global variable. Each function has its own local namespace. Class
methods follow the same scoping rule as ordinary functions. Python makes
uf
educated guesses on whether variables are local or global. It assumes that any
variable assigned a value in a function is local.
Ed
Question 21:
How does a user can share global variables across modules ?
Answer:
The canonical way to share information across modules within a single program is
to create a special module (called config or cfg). Just import the config module in
all modules of application. The module then becomes available as a global name.
Because there is only one instance of each module, any change made to the
module object get reflected everywhere. For example,
https://www.edufever.com/
config. py:
x=0
mod.py:
import config
config.x=1
main.py :
import config
import mod
print config.x
Question 22:
In analog to the example, write a script that asks users for the temperature in F
and prints the temperature in C.
Answer:
m
# Program to convert temperature from F into C.
o
> > > fahrenheit = input (“Entry the temperature
.c
in F : “)
> > > centigrade = (fahrenheit – 32) 8 5/9.0
er
> > > print “The equivalent temperature in centigrade is”, centigrade
ev
Question 23:
Define a function ‘Subtract Number (x, y)’ which takes in two numbers and
Ed
Question 24:
Write a program that takes a number and calculate and display the log, square,
sin and cosine of it.
Answer:
https://www.edufever.com/
# Program to display the various values of a number import math
> > > number = input (“Enter the number :”)
> > > print “Number is”, number
> > > print “Log value of number is” math.log (number)
> > > print “Square of number is”, math.pow (number, 2)
> > > print “Sin value of number is”, math.sin (number)
> > > print “Cosine value of number is”, math.cos (number)
Question 25:
Write a tic-tac-toe program in python. [CBSE Text Book]
Answer:
# tic-tac-toe program
import random def drawboard (board):
# This function is used to print the board
m
print (‘ | | ‘)
print (‘ ‘ + board [7] + ‘ j ‘ + board [8]
o
.c
+ ‘ | ‘ + board [9]) print (‘| | ‘)
print (‘ ‘)
er
print (‘| | ‘)
ev
print (‘ ‘)
Print (‘ | | ‘)
Ed
https://www.edufever.com/
return ‘Player’ def Play Again ():
# This function is used when player wants play again print
(‘Do you want to play again ? (Yes or no)’) return input (), lower ().startswith (‘y’)
def makeMove (board, letter, move): board[move] = letter def is Winner (bo, le):
# This function returns true when plays has
won return
o m
def getBoardcopy(board):
.c
# This function make a duplicate of the board dupeBoard = [ ]
for i in board :
er
dupeBoard.append(i)
ev
return depeBoard
def isSpaceFree (board, move):
uf
https://www.edufever.com/
else:
return – None
def getComputerMove (board, computerletter):
# This function returns the computer’s letter
if computer letter = = ‘X’:
player letter = ‘O’
else:
player letter = ‘X’
for i in range (1,10):
copy = getBoardCopy (board)
if isSpaceFree (copy, i):
makeMove (copy, computerletter, i)
if is Winner (copy, computerletter):
return i
m
for i in range (1,10):
copy = getBoard Copy (board)
if isSpaceFree (copy, i):
o
.c
makeMove (copy, player letter, i)
er
if is Winner (copy, player letter):
return i
ev
return move
Ed
https://www.edufever.com/