Python 1213213
Python 1213213
2) What is PEP 8?
PEP 8 is a coding convention, a set of recommendation, about how to write your Python code
more readable.
6) What are the tools that help to find bugs or perform static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source code and warns
about the style and complexity of the bug. Pylint is another tool that verifies whether the
module
meets the coding standard.
FAQ
1. What is Python? State some programming language features of Python.
Python is a modern powerful interpreted language with objects, modules, threads,
exceptions, and automatic memory managements.
Python was introduced to the world in the year 1991 by Guido van Rossum
Salient features of Python are
-Simple & Easy: Python is simple language & easy to learn.
-Free/open source: it means everybody can use python without purchasing license.
-High level language: when coding in Python one need not worry about low-level details.
-Portable: Python codes are Machine & platform independent.
-Extensible: Python program supports usage of C/ C++ codes.
-Embeddable Language: Python code can be embedded within C/C++ codes & can be used
a scripting language.
-Standard Library: Python standard library contains prewritten tools for programming.
-Build-in Data Structure: contains lots of data structure like lists, numbers & dictionaries.
2. What are the rules for local and global variables in Python?
If a variable is defined outside function then it is implicitly global. If variable is assigned new
value inside the function means it is local. If we want to make it global we need to explicitly
define it as global. Variable referenced inside the function are implicit global. Following code
snippet will explain further the difference
#!/usr/bin/python
# Filename: variable_localglobal.py
def fun1(a):
print 'a:', a
a= 33;
print 'local a: ', a
a = 100
fun1(a)
print 'a outside fun1:', a
def fun2():
global b
print 'b: ', b
b = 33
print 'global b:', b
b =100
fun2()
print 'b outside fun2', b
-------------------------------------------------------
Output
$ python variable_localglobal.py
a: 100
local a: 33
a outside fun1: 100
b :100
global b: 33
b outside fun2: 33
module1.py:
import config
config.a = 1
config.b =2
config.c=3
print “ a, b & resp. are : “ , config.a, config.b, config.c
------------------------------------------------------------------------
output of module1.py will be
123
Following code snippet show usage of all the three functions of module random:
Note: output of this code will be different every time it is executed.
import random
i = random.randint(1,99)# i randomly initialized by integer between range 1 & 99
j= random.uniform(1,999)# j randomly initialized by float between range 1 & 999
k= random.random()# k randomly initialized by float between range 0 & 1
print("i :" ,i)
print("j :" ,j)
print("k :" ,k)
__________
Output -
('i :', 64)
('j :', 701.85008797642115)
('k :', 0.18173593240301023)
Output-
('i :', 83)
('j :', 56.817584548210945)
('k :', 0.9946957743038618)
Tuples are similar to lists, but there data can be changed once created through the execution
of program. Individual element of Tuples can be accessed using indexing.
Sets stores unordered values & have no index. And unlike Tuples and Lists, Sets can have no
duplicate data, It is similar to Mathematical sets.
Dictionary are similar to what their name is. In a dictionary, In python, the word is called a
'key', and the definition a 'value'. Dictionaries consist of pairs of keys and their
corresponding values.
This set of Python Questions & Answers focuses on “Core Data Types”.
Answer:d
Explanation:Class is a user defined datatype.
2. Given a function that does not return any value, What value is thrown by it by
default when executed in shell.
a) int
b) bool
c) void
d) None
Answer:d
Explanation:Python shell throws a NoneType object back.
3. Following set of commands are executed in shell, what will be the output?
>>>str="hello"
>>>str[:2]
>>>str
a) he
b) lo
c) olleh
d) hello
Answer:d
Explanation: Strings are immutable and hence the answer is d.
Answer:a,b
Explanation:Execute help(round) in the shell to get details of the parameters that are passed
into the round function.
Answer:a,b
Explanation:// is integer operation in python 3.0 and int(..) is a type cast operator.
Answer:b
Explanation:Banana is not defined hence name error.
Answer:a
Explanation:Python codes have to be indented properly.
Answer:a
Explanation:List datatype can store any values within it.
10. In order to store values in terms of key and value we use what core datatype.
a) List
b) tuple
c) class
d) dictionary
Answer:d
Explanation:Dictionary stores values in terms of keys and values.
Answer:b,c
Explanation:Carefully look at the colons.
Answer:b,c
Explanation:The \n adds a new line.
13. What is the average value of the code that is executed below ?
>>>grade1 = 80
>>>grade2 = 90
>>>average = (grade1 + grade2) / 2
a) 85
b) 85.0
c) 95
d) 95.0
Answer:b
Explanation:Cause a decimal value to appear as output.
Answer:c,d
Explanation:Execute in the shell.
15. What is the return value of trunc() ?
a) int
b) bool
c) float
d) None
Answer:a
Explanation:Executle help(math.trunc) to get details.
Answer:d
Explanation:+ operator is concatenation operator.
>>>"abcd"[2:]
a) a
b) ab
c) cd
d) dc
Answer:c
Explanation:Slice operation is performed on string.
Answer:b
Explanation:Execute in shell and check.
Answer:d
Explanation:-1 corresponds to the last index.
5. What arithmetic operators cannot be used with strings?
a) +
b) *
c) -
d) **
Answer:c,d
Explanation:+ is used to concatenate and * is used to multiply strings.
Answer:b
Explanation:When prefixed with the letter ‘r’ or ‘R’ a string literal becomes a raw string and
the escape sequences such as \n are not converted.
Answer:c
Explanation:String literals seperated by white space are allowed. They are concatenated.
Answer:c
Explanation:\x is an escape sequence that means the following 2 digits are a hexadicmal
number encoding a character.
Answer:a
Explanation:Execute in shell to verify.
class child(father):
def __init__(self, param):
self.o2 = param
>>>obj = child(22)
>>>print "%d %d" % (obj.o1, obj.o2)
a) None None
b) None 22
c) 22 None
d) Error is generated
Answer:d
Explanation:self.o1 was never created.
>>>temp = tester(12)
>>>print temp.id
a) 224
b) Error
c) 12
d) None
Answer:c
Explanation:id in this case will be the attribute of the class.
Answer:a
Explanation:Execute in the shell and verify.
4. What is the output of the following code ?
>>>example = "snow world"
>>>example[3] = 's'
>>>print example
a) snow
b) snow world
c) Error
d) snos world
Answer:c
Explanation:Strings cannot be modified.
Answer:d
Explanation:Max returns the character with the highest ascii value.
Answer:a
Explanation:l occurs twice in hello.
10. To concatenate two strings to a third what statements are applicable (multiple
answers are allowed) ?
a) s3 = s1 + s2
b) s3 = s1.add(s2)
c) s3 = s1.__add__(s2)
d) s3 = s1 * s2
Answer:a,c
Explanation:__add__ is another method that can be used for concatenation.
Answer:c
Explanation:Execute in the shell to verify.
Answer:b
Explanation:\is used to indicate that the next \ is not an escape sequence.
Answer:d
Explanation:Execute help(string.strip) to find details.
Answer:d
Explanation:Format function returns a string.
Answer:c
Explanation:Cannot concantenate str and int objects.
Answer:c
Explanation:Execute in the shell.
Answer:d
Explanation:Execute in the shell to verify.
Answer:b
Explanation:ascii value of b is one more than a.
Answer:c
Explanation:str is used to represent strings in python.
Answer:a
Explanation:Execute in shell to verify.
2. To retrieve the character at index 3 from string s=”Hello” what command do we
execute (multiple answers allowed) ?
a) s[3]
b) s.getitem(3)
c) s.__getitem__(3)
d) s.getItem(3)
Answer:a, c
Explanation:__getitem(..) can be used to get character at index specified as parameter.
Answer:a,b
Explanation:Execute in shell to verify.
4. If a class defines the __str__(self) method, for an object obj for the class, you
can use which command to invoke the __str__ method.(multiple answers allowed)
a) obj.__str__()
b) str(obj)
c) print obj
d) __str__(obj)
Answer:a,b,c
Explanation:Execute in shell to verify.
Answer:a,b
Explanation:s1 in s2 works in the same way as calling the special function __contains__ .
Answer:b
Explanation:Execute in shell to verify.
7. What is the output of the following code ?
class Count:
def __init__(self, count = 0):
self.__count = count
c1 = Count(2)
c2 = Count(2)
print(id(c1) == id(c2), end = " ")
s1 = "Good"
s2 = "Good"
print(id(s1) == id(s2))
a) True False
b) True True
c) False True
d) False False
Answer:c
Explanation:Execute in the shell objects cannot have same id, however in the case of strings
its different.
firstName = "John"
name = Name(firstName, 'F', "Smith")
firstName = "Peter"
name.lastName = "Pan"
print(name.firstName, name.lastName)
a) Peter Pan.
b) John Pan.
c) Peter Smith.
d) John Smith.
Answer:b
Explanation:Execute in the shell to verify.
Answer:a
Explanation:Execute in shell to verify.
10. Suppose x is 345.3546, what is format(x, “10.3f”) (_ indicates space)
a) __345.355
b) ___345.355
c) ____345.355
d) _____345.354
Answer:b
Explanation:Execute in the shell to verify.
Answer:a,b,c,d
Explanation:Execute in the shell to verify
Answer:a
Explanation:execute in the shell to verify.
Answer:a
Explanation:Execute in the shell and verify.
Answer:c
Explanation:max returns the maximum element in the list.
5. Suppose list1 is [3, 5, 25, 1, 3], what is min(list1) ?
a) 3
b) 5
c) 25
d) 1
Answer:d
Explanation:min returns the minimum element in the list.
Answer:c
Explanation:Sum returns the sum of all elements in the list.
Answer:c
Explanation:Execute in the shell to verify .
Answer:a, b, c, d
Explanation:Slicing is allowed in lists just as in the case of strings.
Answer:c
Explanation:-1 corresponds to the last index in the list.
10. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1] ?
a) [2, 33, 222, 14]
b) Error
c) 25
d) [25, 14, 222, 33, 2]
Answer:a
Explanation:Execute in the shell to verify.
Answer:d
Explanation:Execute in the shell to verify.
names2[0] = 'Alice'
names3[1] = 'Bob'
sum = 0
for ls in (names1, names2, names3):
if ls[0] == 'Alice':
sum += 1
if ls[1] == 'Bob':
sum += 10
print sum
a) 11
b) 12
c) 21
d) 22
View Answer
Answer:b
Explanation:When assigning names1 to names2, we create a second reference to the same
list. Changes to names2 affect names1. When assigning the slice of all elements in names1
to names3, we are creating a full copy of names1 which can be modified independently.
Answer:c
Explanation:Execute in the shell and verify.
Answer:c
Explanation:Execute in the shell to verify.
Answer:a
Explanation:Execute in the shell to verify.
8. To remove string “hello” from list1, we use which command ?
a) list1.remove(“hello”)
b) list1.remove(hello)
c) list1.removeAll(“hello”)
d) list1.removeOne(“hello”)
Answer:a
Explanation:Execute in the shell to verify.
Answer:d
Explanation:Execute in the shell to verify.
2. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after
listExample.extend([34, 5]) ?
a) [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
b) [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
c) [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]
Answer:a
Explanation:Execute in the shell to verify.
Answer:c
Explanation:pop() removes the element at the position specified in the parameter.
Answer:a
Explanation:pop() by default will remove the last element.
Answer:a
Explanation:split() function returns the elements in a list.
Answer:a
Explanation:Execute in the shell to verify.
>>>print(indexOfMax)
a) 1
b) 2
c) 3
d) 4
Answer:a
Explanation:First time the highest number is encountered is at index 1.
Answer:c
Explanation:Execute in the shell to verify.
Answer:b
Explanation:Lists should be copied by executing [:] operation.
v = [1, 2, 3]
f(v)
print(v)
a) [1, 44]
b) [1, 2, 3, 44]
c) [44, 2, 3]
d) [1, 2, 3]
View Answer
Answer:c
Explanation:Execute in the shell to verify.
f(1)
f(2)
v = f(3)
print(v)
a) [1] [2] [3]
b) [1] [1, 2] [1, 2, 3]
c) [1, 2, 3]
d) 1 2 3
Answer:c
Explanation:execute in the shell to verify
Answer:c
Explanation:execute in the shell to verify.
print names2[2][0]
a) None
b) a
c) b
d) c
Answer:d
Explanation:List Comprehension are a shorthand for creating new lists.
Answer:b
Explanation:a list is passed in append so the length is 5.
5. To which of the following the “in” operator can be used to check if an item is in
it?
a) Lists
b) Dictionary
c) Set
d) All of The Above
Answer:d
Explanation:in can be used in all data structures.
Answer:d
Explanation:+ appends all the elements individually into a new list.
mylist = [1, 2, 3, 4]
addItem(mylist)
print len(mylist)
a) 1
b) 4
c) 5
d) 8
View Answer
Answer:c
Explanation:+ will append the element to the list.
values = [1, 2, 3]
print(increment_items(values, 2))
print(values)
a) None
[3, 4, 5]
b) None
[1, 2, 3]
c) [3, 4, 5]
[1, 2, 3]
d) [3, 4, 5]
None
Answer:a
Explanation:Execute in the shell to verify.
Answer:a
Explanation:Run the code to get a better understanding with many arguements.
Answer:c
Explanation:Execute in the shell to verify.
print(v)
a) 3
b) 5
c) 6
d) 33
Answer:d
Explanation:Execute in the shell to verify.
print(v)
a) 1
b) 3
c) 5
d) 6
Answer:a
Explanation:Execute in the shell to verify.
Answer:d
Explanation:Execute in the shell to verify.
Answer:d
Explanation:Execute in the shell to verify.
for row in m:
for element in row:
if v < element: v = element
return v
print(ttt(data[0]))
a) 1
b) 2
c) 4
d) 5
Answer:c
Explanation:Execute in the shell to verify.
Answer:a
Explanation:In can be used to check if the key is int dictionary.
Answer:b
Explanation:If d2 was initialized as d2 = d1 the answer would be true.
Answer:c
Explanation:Arithmetic > operator cannot be used with dictionaries.
Answer:a
Explanation:Execute in the shell to verify.
Answer:c
Explanation:Execute in the shell to verify.
Answer:b
Explanation:Execute in the shell to verify.
Answer:b
Explanation:Tuples are characterised by their round brackets.
Answer:b
Explanation:Values cannot be modified in the case of tuple.
Answer:c
Explanation:Slicing just as in the case of strings takes place in tuples.
Answer:c
Explanation:Slicing just as in the case of strings takes place in tuples.
5. What will be the output?
>>>t = (1, 2, 4, 3, 8, 9)
>>>[t[i] for i in range(0, len(t), 2)]
a) [2, 3, 9]
b) [1, 2, 4, 3, 8, 9]
c) [1, 4, 8]
d) (1, 4, 8)
Answer:c
Explanation:Execute in the shell to verify.
Answer:b
Explanation:Elements are compared one by one in this case.
Answer:d
Explanation:Tuples are immutable and don’t have an append method. An exception is
thrown in this case..
10. What will be the output?
numberGames = {}
numberGames[(1,2,4)] = 8
numberGames[(4,2,1)] = 10
numberGames[(1,2)] = 12
sum = 0
for k in numberGames:
sum += numberGames[k]
Answer:b
Explanation:Execute help(open) to get more details.
Answer:b
Explanation:w is used to indicate that file is to be written to.
Answer:a
Explanation:a is used to indicate that data is to be apended.
Answer:a
Explanation:Execute in the shell to verify.
6. To read the entire remaining contents of the file as a string from a file object
infile, we use
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
Answer:b
Explanation:read function is used to read all the lines in a file.
print f.closed
a) True
b) False
c) None
d) Error
Answer:a
Explanation:The WITH statement when used with open file guarantees that the file object is
closed when the with block exits..
8. To read the next line of the file from a file object infile, we use
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
Answer:c
Explanation:Execute in the shell to verify.
9. To read the remaining lines of the file from a file object infile, we use
a) infile.read(2)
b) infile.read()
C) infile.readline()
d) infile.readlines()
Answer:d
Explanation:Execute in the shell to verify.
This section on Python aptitude questions and answers focuses on “Function – 2″.
Answer: a, b and c
Explanation: Functions can be defined inside a module, a class or another function.
Answer: d
Explanation: None.
Answer: a
Explanation: Each object in Python has a unique id. The id() function returns the object’s id.
Answer: a
Explanation: Functions that are always available for usage, functions that are contained
within external modules, which must be imported and functions defined by a programmer
with the def keyword.
Eg: math import sqrt
The sqrt() function is imported from the math module.
x = cube(3)
print x
a) 9
b) 3
c) 27
d) 30
View Answer
Answer: c
Explanation: A function is created to do a specific task. Often there is a result from such a
task. The return keyword is used to return values from a function. A function may or may not
return a value. If a function does not
def C2F(c):
return c * 9/5 + 32
print C2F(100)
print C2F(0)
a) 212
32
b) 314
24
c) 567
98
d) None of the mentioned
Answer: a
Explanation: None.
Answer: b
Explanation: The arguments in Python functions may have implicit values. An implicit value
is used, if no value is provided. Here we created a power function. The function has one
argument with an implicit value. We can call
the function with one or two arguments.
Answer: a
Explanation: We use the * operator to indicate, that the function will accept arbitrary number
of arguments. The sum() function will return the sum of all arguments. The first string in the
function body is called the
function documentation string. It is used to document the function. The string must be in
triple quotes.
This section on Python aptitude questions and answers focuses on “Function – 3″.
Answer: a
Python supports the creation of anonymous functions (i.e. functions that are not bound to a
name) at runtime, using a construct called lambda. Lambda functions are restricted to a
single expression. They can be used wherever
normal functions can be used.
Answer: a
Explanation: The lambda keyword creates an anonymous function. The x is a parameter,
that is passed to the lambda function. The parameter is followed by a colon character. The
code next to the colon is the expression that is executed, when the lambda function is
called. The lambda function is assigned to the z variable.
The lambda function is executed. The number 8 is passed to the anonymous function and it
returns 48 as the result. Note that z is not a name for this function. It is only a variable to
which the anonymous function was
assigned.
Answer: c
Explanation: None.
Answer: b
Explanation: lambda definition does not include a return statement — it always contains an
expression which is returned. Also note that we can put a lambda definition anywhere a
function is expected, and we don’t have to
assign it to a variable at all.
5. Lambda is a statement.
a) True
b) False
Answer: b
Explanation: None.
Answer: b
Explanation: None.
Answer: a
Explanation: None.
who = writer()
who('Arthur')
a) Arthur Sir
b) Sir Arthur
c) Arthur
d) None of the mentioned
Answer: b
Explanation: None.
for f in L:
print(f(3))
a) 27
81
343
b) 6
9
12
c) 9
27
81
d) None of the mentioned
Answer: c
Explanation: None.
Answer: c
Explanation: None.
Below are top 20 Python interview questions, frequently asked to fresher and
amateur Python programmers.
Python programs are written to files with extension .py . These python source code files are
compiled to byte code (python specific representation and not binary code), platform
independent form stored in .pyc files. These
byte code helps in startup speed optimization. These byte code are then subjected to Python
Virtual Machine PVM where one by one instructions are read and executed. This is
interpreter.
object.
During execution, when a name is referred, python uses LEGB rule to find out the object. It
starts looking out first into the local namespace. Then it searches name in enclosed
namespace created by nested def and lambda. Then
into global namespace which is the module in which it is defined and then finally into built-in
namespace.
Example 1:
>>> def addxy(x,y): # x, y are local. addxy is global
... temp=x+y # temp is local
... print temp
... return temp
...
>>> addxy(1,2)
3
3
Example 2:
>>> total = 0 # total is global
>>> def addxy(x,y):
... global total
... total = x+y
...
>>> x
100
>>> y
200
>>> addxy(x,y)
>>> total
300
Example:
def add(x,y, *tup):
temp = x+y
for elem in tup:
temp = temp + elem
return temp
Example:
def percentage(mks1, mks2, **dict):
total_mks = mks1 + mks2
return total_mks / float( dict['out_of'] )
A copy module overcomes above problem by providing copy() and deepcopy(). copy()
creates a copy of an object, creating a separate entity.
Example of shallow copy copy():
>>> import copy
>>> copied_l = copy.copy(l) # performs shallow copy
>>> copied_l.pop(0)
2
>>> copied_l
[3]
>>> l
[2, 3]
copy() does not perform recursive copy of object. It fails for compound object types.
Example program for shallow copy problems:
>>> l
[[1, 2, 3], ['a', 'b', 'c']]
>>> s_list=copy.copy(l) # performs shallow copy
>>> s_list
[[1, 2, 3], ['a', 'b', 'c']]
>>> s_list[0].pop(0)
1
>>> s_list
[[2, 3], ['a', 'b', 'c']]
>>> l
[[2, 3], ['a', 'b', 'c']] # problem of shallow copy on compund object types
To overcome this problem, copy module provides deepcopy(). deepcopy() creates and
returns deep copy of compound object (object containing other objects)
Example for deep copy deepcopy():
>>> l
[[1, 2, 3], ['a', 'b', 'c']]
>>> deep_l = copy.deepcopy(l)
>>> deep_l
[[1, 2, 3], ['a', 'b', 'c']]
>>> deep_l[0].pop(0)
1
>>> deep_l
[[2, 3], ['a', 'b', 'c']]
>>> l
[[1, 2, 3], ['a', 'b', 'c']]
def func1():
a=1
b=1
b=a-b
print "Attempt 2: a="+str(a)+", b="+str(b)
try:
func2(a,b)
except ZeroDivisionError:
print "Caller handling exception"
func1()
Output:
Attempt 1: a=1, b=1
Always executed
Attempt 2: a=1, b=0
Exception caught. Why is b = 0? Rethrowing. Please handle
Always executed
Caller handling exception
11. Give a regular expression that validates email id using python regular
expression module re
Python provides a regular expression module re
Here is the re that validates a email id of .com and .co.in subdomain:
re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com")
1. iterator.__iter__() :
It returns the iterator object itself. This is required to allow both containers and iterators to
be used with the for and in statements.
2. iterator.__next__() :
It returns the next item from the container. If there are no further items, raise the
StopIteration exception.
Iterators are required to implement __iter__ which returns the iterator (self) . Hence it can be
used with for in
iterator known as generator. To get the next value from a generator, we use the same built-
in function as for iterators: next() . next() takes care of calling the generator's __next__()
method.
When a generator function calls yield, the "state" of the generator function is frozen; the
values of all variables are saved and the next line of code to be executed is recorded until
next() is called again. Once it is, the
generator function simply resumes where it left off. If next() is never called again, the state
recorded during the yield call is (eventually) discarded.
Example of generators:
def gen_func_odd_nums():
odd_num = 1
while True:
yield odd_num # saves context and return from function
odd_num = odd_num + 2
generator_obj = gen_func_odd_nums();
print "First 10 odd numbers:"
for i in range(10):
print next(generator_obj) # calls generator_obj.__next__()
Output:
First 10 odd numbers:
1
3
5
7
9
11
13
15
17
19
If the base class is present in other module, the syntax for derivation changes to:
class DeriveClass( module.BaseClass):
Python supports overriding of base class functions by derive class. This helps in adding more
functionality to be added in overriden function in derived class if required.
where an attribute if not found in DeriveClass are then searched in BaseClass1 and their
parent then BaseClass2 and their parents and so on. With new style, Python avoids diamond
problem of reaching common base class from
multiple paths by lineraly searching base classes in left to right order.
1. Define python?
Python is simple and easy to learn language compared to other programming languages.
Python was introduced to the world in the year 1991 by Guido van Rossum. It is a dynamic
object oriented language used for developing
software. It supports various programming languages and have a massive library support for
many other languages. It is a modern powerful interpreted language with objects, modules,
threads, exceptions, and automatic memory managements.
3. Define self?
'self' is a conventional name of method’s first argument. A method which is defined as
meth(self, x ,y ,z) is called as a.meth(x, y, z) for an instance of a class in which definition
occurs and is called as meth(a, x ,y, z).
5. Is there any tool used to find bugs or carrying out static analysis?
Yes. PyChecker is the static analysis tool used in python to find bugs in source code, warns
about code style and complexity etc. Pylint is a tool that verifies whether a module satisfies
standards of coding and makes it
possible to add custom feature and write plug-ins.
9. Define class?
Class is a specific object type created when class statement is executed. To create instances
objects, class objects can be used as templates which represent both code and data specific
to datatype. In general, a class is
based on one or many classes known as base classes. It inherits methods and attributes of
base classes. An object model is now permitted to redefine successively using inheritance.
Basic accessor methods are provided by
generic Mailbox for subclasses and mailbox like MaildirMailbox, MboxMailbox,
OutlookMailbox which handle many specific formats of mailbox.
module1.py:
import config
config.a = 1
config.b =2
config.c=3
print “ a, b & resp. are : “ , config.a, config.b, config.c
------------------------------------------------------------------------
output of module1.py will be
123
13. How can we pass optional or keyword parameters from one function to
another in Python?
Gather the arguments using the * and ** specifiers in the function’s parameter list. This
gives us positional arguments as a tuple and the keyword arguments as a dictionary. Then
we can pass these arguments while calling
Python program runs directly from the source code. Each type Python programs are
executed code is required. Python converts source code written by the programmer into
intermediate language which is again translated it into the native language / machine
language that is executed. So Python is an Interpreted language.
import cgi
form = cgi.FieldStorage()
if not (form.has_key("name") and form.has_key("age")):
print "<H1>Name & Age not Entered</H1>"
print "Fill the Name & Age accurately."
return
print "<p>name:", form["name"].value
print "<p>Age:", form["age"].value
import Cookie
ck= Cookie.SimpleCookie ( x )
21. When do you use list vs. tuple vs. dictionary vs. set?
List and Tuple are both ordered containers. If you want an ordered container of constant
elements use tuple as tuples are immutable objects.
22. When you need ordered container of things, which will be manipulated, use
lists.
Dictionary is key, value pair container and hence is not ordered. Use it when you need fast
access to elements, not in ordered fashion. Lists are indexed and index of the list cannot be
“string” e.g. list [‘myelement’] is not a valid statement in python.
25. What is used to represent Strings in Python? Is double quotes used for String
representation or single quotes used for String representation in Python?
27. Which of the languages does Python resemble in its class syntax?
C++ is the appropriate language that Python resemble in its class syntax.
28. Does Python support strongly for regular expressions? What are the other
languages that support strongly for regular expressions?
Yes, python strongly support regular expression. Other languages supporting regular
expressions are: Delphi, Java, Java script, .NET, Perl, Php, Posix, python, Ruby, Tcl, Visual
Basic, XML schema, VB script, Visual Basic 6.
Objects referenced from the global namespaces of Python modules are not always de-
allocated when Python exits. This may happen if there are circular references. There are also
certain bits of memory that are allocated by the
C library that are impossible to free (e.g. a tool like the one Purify will complain about these).
Python is, however, aggressive about cleaning up memory on exit and does try to destroy
every single object.
If you want to force Python to delete certain things on de-allocation, you can use the at exit
module to register one or more exit functions to handle those deletions.
statement.
def fun():
y=2333.3
x=str(y)
z=repr(y)
print " y :",y
print "str(y) :",x
print "repr(y):",z
fun()
-------------
output
y : 2333.3
str(y) : 2333.3
repr(y) : 2333.3000000000002
Python contains several built-in functions to convert values from one data type to another
data type.
The int function takes string and coverts it to an integer.
s = "1234" # s is string
i = int(s) # string converted to int
print i+2
------------------------
1236
The float function converts strings into float number.
s = "1234.22" # s is string
i = float(s) # string converted to float
print i
-------------------------
1234.22
The second approach is to create a list of the desired length first and then fill in each
element with a newly created lists demonstrated below :
>>>list=[0]*3
>>>for i in range(3):
>>> list[i]=[0]*2
>>>for i in range (3):
>>> for j in range(2):
>>> list[i][j] = i+j
>>>print list
__________________________
Output
[[0, 1], [1, 2], [2, 3]]
e1 = Employee("Sarah",99,30000.00)
e2 = Employee("Asrar",100,60000.00)
print("Employee Details:")
Employee Details:
(' Name:', 'Sarah', 'Code:', 99, 'Pay:', 30000.0)
(' Name:', 'Asrar', 'Code:', 100, 'Pay:', 60000.0)
Following code snippet show usage of all the three functions of module random:
Note: output of this code will be different evertime it is executed.
import random
i = random.randint(1,99)# i randomly initialized by integer between range 1 & 99
j= random.uniform(1,999)# j randomly initialized by float between range 1 & 999
k= random.random()# k randomly initialized by float between range 0 & 1
print("i :" ,i)
print("j :" ,j)
print("k :" ,k)
__________
Output -
('i :', 64)
('j :', 701.85008797642115)
('k :', 0.18173593240301023)
Output-
('i :', 83)
('j :', 56.817584548210945)
('k :', 0.9946957743038618)
42. What is the optional statement used in a try except statement in Python?
There are two optional clauses used in try except statements:
1. Else clause: It is useful for code that must be executed when the try block does not create
any exception
2. Finally clause: It is useful for code that must be executed irrespective of whether an
exception is generated or not.
45. Which all are the operating system that Python can run on?
Python can run of every operating system like UNIX/LINUX, Mac, Windows, and others.
46. What is the statement that can be used in Python if a statement is required
syntactically but the program requires no action?
Pass is a no-operation/action statement in python
If we want to load a module and if it does not exist, let us not bother, let us try to do other
task. The following example demonstrates that.
Try:
Import module1
Except:
Pass
49. Does python support switch or case statement in Python? If not what is the
reason for the same?
No. You can use multiple if-else, as there is no need for this.
54. Which of the languages does Python resemble in its class syntax?
C++ is the appropriate language that Python resemble in its class syntax.
1 line: Output
print 'Hello, world!'
5 lines: Functions
def greet(name):
print 'Hello', name
greet('Jack')
greet('Jill')
greet('Bob')
with open(file_name) as f:
for line in f:
print ' ' + line.rstrip()
time_now = localtime()
hour = time_now.tm_hour
12 lines: Classes
class BankAccount(object):
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def overdrawn(self):
return self.balance < 0
my_account = BankAccount(15)
my_account.withdraw(5)
print my_account.balance
15 lines: itertools
from itertools import groupby
lines = '''
This is the
first paragraph.
for r, c in reversed(queens):
left, right = left - 1, right + 1
def solve(n):
if n == 0:
return [[]]
smaller_solutions = solve(n - 1)
return [solution+[(n,i+1)]
for i in xrange(BOARD_SIZE)
for solution in smaller_solutions
if not under_attack(i+1, solution)]
for answer in solve(BOARD_SIZE):
print answer
for p in iter_primes():
if p > 1000:
break
print p
def validate(queens):
left = right = col = queens[-1]
for r in reversed(queens[:-1]):
left, right = left-1, right+1
if r in (left, col, right):
raise BailOut
def add_queen(queens):
for i in range(BOARD_SIZE):
test_queens = queens + [i]
try:
validate(test_queens)
if len(test_queens) == BOARD_SIZE:
return test_queens
else:
return add_queen(test_queens)
except BailOut:
pass
raise BailOut
queens = add_queen([])
print queens
print "\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) for q in queens)
guesses_made += 1
if guess == number:
break
if guess == number:
print 'Good job, {0}! You guessed my number in {1} guesses!'.format(name,
guesses_made)
else:
print 'Nope. The number I was thinking of was {0}'.format(number)
=======================================================
========
Here is a set of small scripts, which demonstrate some features of
Python programming.
# this is the first comment
#! python
# integer variables
SPAM = 1
#! python
print "Hello, Python"
#! python
# string variable
STRING = "# This is not a comment."
print STRING
#! python
# integer arith
a=4
print a
b=12+5
print b
c=b%a
print c
#! python
# trailing comma
i = 256*256
print 'The value of i is', i
#! python
# Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
while b < 200:
print b,
a, b = b, a+b
#! python
# input and operator if
x = int(raw_input("Please enter an integer: "))
if x < 0:
x=0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
#! python
# operator for:
# Measure some strings:
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
#! python
# range function
print range(10)
print range(5, 10)
print range(0, 10, 3)
#! python
# break operator
# prime numbers
#! python
#pass statement does nothing.
#It can be used when a statement is required syntactically but the program requires no
action. For example:
while True:
pass # Busy-wait for keyboard interrupt
#! python
# Defining Functions
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
# Now call the function we just defined:
fib(2000)
! python
#===================================
f100 = fib2(100) # call it
print f100 # write the result
#! python
# work with strings
# Strings can be concatenated (glued together) with the + operator, and repeated with *:
word = 'Help' + 'A'
print word
print '<' + word*5 + '>'
print word[4]
print word[0:2]
print word[2:4]
# Slice indices have useful defaults; an omitted first index defaults to zero,
# an omitted second index defaults to the size of the string being sliced.
# Python strings cannot be changed. Assigning to an indexed position in the string results in
an error:
# However, creating a new string with the combined content is easy and efficient:
# Degenerate slice indices are handled gracefully: an index that is too large is replaced
# by the string size, an upper bound smaller than the lower bound returns an empty string.
print word[1:100]
print word[10:]
print word[2:1]
# Indices may be negative numbers, to start counting from the right. For example:
print word[-1] # The last character
print word[-2] # The last-but-one character
print word[-2:] # The last two characters
print word[:-2] # All but the last two characters
# But note that -0 is really the same as 0, so it does not count from the right!
print word[-0] # (since -0 equals 0)
# Out-of-range negative slice indices are truncated, but don't try this for single-element
(non-slice) indices:
print word[-100:]
#The best way to remember how slices work is to think of the indices as pointing between
characters,
#with the left edge of the first character numbered 0. Then the right edge of the last
character
#of a string of n characters has index n, for example:
# +---+---+---+---+---+
#|H|e|l|p|A|
# +---+---+---+---+---+
#0 1 2 3 4 5
#-5 -4 -3 -2 -1
s = 'supercalifragilisticexpialidocious'
print s
print len(s)
#! python
# Default Argument Values
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return True
if ok in ('n', 'no', 'nop', 'nope'): return False
retries = retries - 1
if retries < 0: raise IOError, 'refusenik user'
print complaint
#======================================================
========
i=5
def f(arg=i):
print arg
i=6
f()
#======================================================
========
z=ask_ok('really quit???')
if z==False :
print "bad"
#! python
# Lambda Forms
def make_incrementor(n):
return lambda x: x + n
#==================================
f = make_incrementor(42)
print f(0)
print f(1)
print f(15)
//=======================================================
============================
//
//=======================================================
============================
#! python
# speed test
nn=10000000
i=0;
s=0;
print "beginning..."
while i
#! python
#! python
# math
import math
print math.cos(math.pi / 4.0)
print math.log(1024, 2)
#! python
# random
import random
print random.choice(['apple', 'pear', 'banana'])
print random.sample(xrange(100), 10) # sampling without replacement
print random.random() # random float
print random.randrange(6) # random integer chosen from range(6)
#! python
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = [] # here is new list with all permutations!
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
#==============================================
a=[1,2,3]
print perm(a)
#! python
a=2+3j
b=2-3j
print a*a
print a*b
print a.real
print b.imag
#! python
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops! That was no valid number. Try again..."
#! python
import string, sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(string.strip(s))
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
#! python
# work with lists
a = ['spam', 'eggs', 100, 1234]
print " list a=",a
#Assignment to slices is also possible, and this can even change the size of the list:
# Replace some items:
a[0:2] = [1, 12]
print a
# Remove some:
a[0:2] = []
print a
# Insert some:
a[1:1] = ['bletch', 'xyzzy']
print a
print p[1][0]
p[1].append('xtra')
print p
print q
#! python
# more work with lists
a = [66.6, 333, 333, 1, 1234.5]
print a.count(333), a.count(66.6), a.count('x')
a.insert(2, -1)
print a
a.append(333)
print a
print a.index(333)
a.remove(333)
print a
a.reverse()
print a
a.sort()
print a
#! python
# huge list making
nn=1000000
a = []
i=0
while i
#! python
# Using Lists as Stacks
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print stack
x=stack.pop()
print "popped ",x
print stack
x=stack.pop()
print "popped ",x
x=stack.pop()
print "popped ",x
print stack
#! python
# Using Lists as Queues
s=queue.pop(0)
print s
s=queue.pop(0)
print s
print queue
#! python
# The del statement
a = [-1, 1, 66.6, 333, 333, 1234.5]
del a[0]
print a
del a[2:4]
print a
#! python
# filter of sequence
#! python
# map of sequence
def cube(x): return x*x*x
res=map(cube, range(1, 11))
print res
#! python
# reduce(func, sequence)" returns a single value constructed by
# calling the binary function func on the first two items of the sequence,
# then on the result and the next item, and so on
def add(x,y): return x+y
r=reduce(add, range(1, 11))
print r # 55
#! python
# A tuple consists of a number of values separated by commas
t = 12345, 54321, 'hello!' # tuple packing
print t[0]
print t
(12345, 54321, 'hello!')
#! python
# Dictionaries are sometimes as ``associative memories'' or ``associative arrays''
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print tel
print tel['jack']
del tel['sape']
tel['irv'] = 4127
print tel
print tel.keys()
x=tel.has_key('guido')
print x
vec=[1,2,3,4,5]
dd=dict([(x, x**2) for x in vec]) # use a list comprehension
print dd
#! python
# Standard Module sys
import sys
print sys.path
sys.path.append('c:\temp')
print sys.path
print sys.version
print sys.platform
print sys.maxint
#! python
#======================================================
=
# dir() is used to find out which names a module defines
import sys
print dir(sys)
# Without arguments, dir() lists the names you have defined currentl
#! python
# convert any value to a string: pass it to the repr() or str()
s = 'Hello, world.'
print str(s)
print repr(s)
print str(0.1)
print repr(0.1)
x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print s
#! python
# two ways to write a table of squares and cubes:
print '================================================='
for x in range(1,11):
print '%2d %3d %4d' % (x, x*x, x*x*x)
#! python
# output results from running "python demo.py one two three"
# at the command line:
import sys
print sys.argv[] # ['demo.py', 'one', 'two', 'three']
#! python
# String Pattern Matching - regular expression
import re
r=re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
print r # ['foot', 'fell', 'fastest']
#! python
# dates are easily constructed and formatted
from datetime import date
now = date.today()
print now
datetime.date(2003, 12, 2)
print now.strftime("%m-%d-%y or %d%b %Y is a %A on the %d day of %B")
#! python
# Internet Access
import urllib2
for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
if 'EST' in line: # look for Eastern Standard Time
print line
import smtplib
server = smtplib.SMTP('localhost')
server.sendmail('soothsayer@tmp.org', 'jceasar@tmp.org',
"""To: jceasar@tmp.org
From: soothsayer@tmp.org
Beware the Ides of March.
""")
server.quit()
f=open('c:/TEMP/workpy.txt','w')
print f
f.write("aaaaaaaaaaaaaaaaaaa\n")
f.write("bbbbbbbbbbbbbb");
f.close()
# pieces reading
s1=f.read(5)
print s1
s2=f.read(19)
print s2
s2=f.read(25)
print s2
f.close()
# pieces reading
s1=f.read(5)
print s1
print f.tell()
s2=f.read(19)
print s2
print f.tell()
s2=f.read(25)
print s2
print f.tell()
f.close()
#! python
# The glob module provides a function for making file lists from
# directory wildcard searches:
import glob
s=glob.glob('*.*')
print s # ['primes.py', 'random.py', 'quote.py']