Python Interview Questions
Python Interview Questions
Python Interview Questions
iterable.
11) What are the built-in type does python provides?
There are mutable and Immutable types of Pythons built in types Mutable built-in types
List
Sets
Dictionaries
Immutable built-in types
Strings
Tuples
Numbers
12) What is namespace in Python?
In Python, every name introduced has a place where it lives and can be hooked for. This is
known as namespace. It is like a box where a variable name is mapped to the object placed.
Whenever the variable is searched out, this box will be searched, to get corresponding
object.
13) What is lambda in Python?
It is a single expression anonymous function often used as inline function.
14) Why lambda forms in python does not have statements?
A lambda form in python does not have statements as it is used to make new function object
and then return them at runtime.
15) What is pass in Python?
Pass means, no-operation Python statement, or in other words it is a place holder in
compound
statement, where there should be a blank left and nothing has to be written there.
16) In Python what are iterators?
In Python, iterators are used to iterate a group of elements, containers like list.
17) What is unittest in Python?
A unit testing framework in Python is known as unittest. It supports sharing of setups,
automation testing, shutdown code for tests, aggregation of tests into collections etc.
18) In Python what is slicing?
A mechanism to select a range of items from sequence types like list, tuple, strings etc. is
known as slicing.
19) What are generators in Python?
The way of implementing iterators are known as generators. It is a normal function except
that
it yields expression in the function.
20) What is docstring in Python?
A Python documentation string is known as docstring, it is a way of documenting Python
functions, modules and classes.
21) How can you copy an object in Python?
To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general
case.
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
3. How do we share global variables across modules in Python?
We can create a config file & store the entire global variable to be shared across modules or
script in it. By simply importing config, the entire global variable defined it will be available
for use in other modules.
For example I want a, b & c to share between modules.
config.py :
a=0
b=0
c=0
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
4. How is memory managed in python?
Memory management in Python involves a private heap containing all Python objects and
data structures. Interpreter takes care of Python heap and that the programmer has no
access to it.
The allocation of heap space for Python objects is done by Python memory manager. The
core API of Python provides some tools for the programmer to code reliable and more robust
program.
Python also has a build-in garbage collector which recycles all the unused memory. When an
object is no longer referenced by the program, the heap space it occupies can be freed. The
garbage collector determines objects which are no longer referenced by the program frees
the occupied memory and make it available to the heap space.
The gc module defines functions to enable /disable garbage collector:
gc.enable() -Enables automatic garbage collection.
gc.disable() - Disables automatic garbage collection.
5. Describe how to generate random numbers in Python.
The standard module random implements a random number generator.
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, b].
random()returns a floating point number in the range [0, 1].
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)
6. Describe how exceptions are handled in python.
Errors detected during execution of program are called exceptions. Exceptions can be
handled using the try..except statement. We basically put our usual statements within the
try-block and put all our error handlers in the except-block.
tryexcept demo code:
>>> while True:
try:
x = int(raw_input("Enter no. of your choice: "))
break
except ValueError:
print "Oops! Not a valid number. Attempt again"
Enter no. of your choice: 12ww
Oops! Not a valid number. Attempt again
Enter no. of your choice: hi there
Oops! Not a valid number. Attempt again
Enter no. of your choice: 22
>>>
7. When to use list vs. tuple vs. dictionary vs. set?
List is like array, it can be used to store homogeneous as well as heterogeneous data type (It
can store same data type as well as different data type). List are faster compared to array.
Individual element of List data can be accessed using indexing & can be manipulated.
List Code Snippet:
list = ["Sarah",29,30000.00]
for i in range (3):
print list[i]
-----------------Output
Sarah
29
30000.0
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.
Tuples Code Snippet: The Days
days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
print days
-----------------------------('Sunday', 'Mondays', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
Sets stores unordered values & have no index. And unlike Tuples and Lists, Sets can have no
duplicate data, It is similar to Mathematical sets.
add() function can be used to add element to a set.
update() function can be used to add a group of elements to a set.
Copy() function can be used to create clone of set.
Set Code Snippet:
disneyLand = set (['Minnie Mouse', 'Donald Duck', 'Daisy Duck', 'Goofy'])
disneyLand.add('Pluto')
print disneyLand
----------------------------------------------Output
set(['Goofy', 'Daisy Duck', 'Donald Duck', 'Minnie Mouse', Pluto])
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.
Dictionary Code Snippet:
>>> dict = {'India': 'Bharat', 'Angel': Mother Teresa, 'Cartoon': 'Mickey'}
>>>print dict[India]
Bharat
>>>print dict[Angel]
Mother Teresa
8. Explain the disadvantages of python.
Disadvantages of Python are:
Answer:a
Explanation:Execute help(id) to find out details in python shell.id returns a integer value that
is unique.
6. In python we do not specify types,it is directly interpreted by the compiler, so
consider the following operation to be performed.
>>>x = 13 ? 2
objective is to make sure x has a integer value, select all that apply (python 3.xx)
a) x = 13 // 2
b) x = int(13 / 2)
c) x = 13 / 2
d) x = 13 % 2
Answer:a,b
Explanation:// is integer operation in python 3.0 and int(..) is a type cast operator.
7. What error occurs when you execute?
apple = mango
a) SyntaxError
b) NameError
c) ValueError
d) TypeError
Answer:b
Explanation:Banana is not defined hence name error.
8. Carefully observe the code and give the answer.
def example(a):
a = a + '2'
a = a*2
return a
>>>example("hello")
a) indentation Error
b) cannot perform mathematical operation on strings
c) hello2
d) hello2hello2
View Answer
Answer:a
Explanation:Python codes have to be indented properly.
9. What dataype is the object below ?
L = [1, 23, 'hello', 1]
a) List
b) dictionary
c) array
d) tuple
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.
11. Which of the following results in a SyntaxError(Multiple answers possible) ?
a) Once upon a time, she said.
b) He said, Yes!"
c) 3\
d) Thats okay
Answer:b,c
Explanation:Carefully look at the colons.
12. The following is displayed by a print function call:
tom
dick
harry
Select all of the function calls that result in this output
a) print(tom
\ndick
\nharry)
b) print(tom
dick
harry)
c) print(tom\ndick\nharry)
d) print(tom
dick
harry)
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.
14. Select all options that print
hello-how-are-you
a) print(hello, how, are, you)
b) print(hello, how, are, you + - * 4)
c) print(hello- + how-are-you)
d) print(hello + - + how + - + are + - + you)
Answer:c,d
Explanation:Execute in the shell.
a) 0xA0xB0xC
b) Error
c) 022
d) 33
Answer:d
Explanation:0xA and 0xB and 0xC are hexadecimal integer literals representing the decimal
values 10,11 and 12 respectively. There sum is 33.
This set of Python Questions & Answers focuses on Strings.
1. What is the output of the following code ?
class father:
def __init__(self, param):
self.o1 = param
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.
2. What is the output of the following code ?
class tester:
def __init__(self, id):
self.id = str(id)
id="224"
>>>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.
3. What is the output of the following code ?
>>>example = "snow world"
>>>print "%s" % example[4:7]
a) wo
b) world
c) sn
d) rl
Answer:a
Explanation:Execute in the shell and verify.
b) True
c) -1
d) None
Answer:b
Explanation:Starts with checks if the given string starts with the parameter that is passed.
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.
This set of Python Questions & Answers focuses on Strings.
1. What is the output when following statement is executed ?
>>>chr(ord('A'))
a) A
b) B
c) a
d) Error
Answer:a
Explanation:Execute in shell to verify.
2. What is the output when following statement is executed ?
>>>print(chr(ord('b')+1))
a) a
b) b
c) c
d) A
View Answer
Answer:c
Explanation:Execute in the shell to verify.
3. Which of the following statement prints hello\example\test.txt ?
a) print(hello\example\test.txt)
b) print(hello\\example\\test.txt)
c) print(hello\example\test.txt)
d) print(hello\example\test.txt)
Answer:b
Explanation:\is used to indicate that the next \ is not an escape sequence.
4. Suppose s is \t\tWorld\n, what is s.strip() ?
a) \t\tWorld\n
b) \t\tWorld\n
c) \t\tWORLD\n
d) World
Answer:d
Explanation:Execute help(string.strip) to find details.
5. The format function returns :
a) Error
b) int
c) bool
d) str
Answer:d
Explanation:Format function returns a string.
6. What is the output of hello+1+2+3 ?
a) hello123
b) hello
c) Error
d) hello6
Answer:c
Explanation:Cannot concantenate str and int objects.
7. What is the output when following code is executed ?
>>>print("D", end = ' ')
>>>print("C", end = ' ')
>>>print("B", end = ' ')
>>>print("A", end = ' ')
a) DCBA
b) A, B, C, D
c) D C B A
d) A, B, C, D will be displayed on four lines
Answer:c
Explanation:Execute in the shell.
8. What is the output when following statement is executed ?(python 3.xx)
>>>print(format("Welcome", "10s"), end = '#')
>>>print(format(111, "4d"), end = '#')
>>>print(format(924.656, "3.2f"))
a) Welcome# 111#924.66
b) Welcome#111#924.66
c) Welcome#111#.66
d) Welcome # 111#924.66
Answer:d
Explanation:Execute in the shell to verify.
9. What will be displayed by print(ord(b) ord(a)) ?
a) 0
b) 1
c) -1
d) 2
Answer:b
Explanation:ascii value of b is one more than a.
10. Say s=hello what will be the return value of type(s) ?
a) int
b) bool
c) str
d) String
Answer:c
Explanation:str is used to represent strings in python.
This set of Python Questions & Answers focuses on Strings.
1. What is Hello.replace(l, e)
a) Heeeo
b) Heelo
c) Heleo
d) None
View Answer
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.
3. To return the length of string s what command do we execute (multiple answers
allowed) ?
a) s.__len__()
b) len(s)
c) size(s)
d) s.size()
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.
5. To check whether string s1 contains s2, use
a) s1.__contains__(s2)
b) s1 in s2
c) s1.contains(s2)
d) si.in(s2)
Answer:a,b
Explanation:s1 in s2 works in the same way as calling the special function __contains__ .
6. Suppose i is 5 and j is 4, i + j is same as
a) i.__add(j)
b) i.__add__(j)
c) i.__Add(j)
d) i.__ADD(j)
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.
8. What is the output of the following code ?
class Name:
def __init__(self, firstName, mi, lastName):
self.firstName = firstName
self.mi = mi
self.lastName = lastName
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.
9. What function do you use to read a string?
a) input(Enter a string)
b) eval(input(Enter a string))
c) enter(Enter a string)
d) eval(enter(Enter a string))
Answer:a
Explanation:Execute in shell to verify.
a) 1
b) 9
c) 15
d) Error
Answer:c
Explanation:Sum returns the sum of all elements in the list.
7. To shuffle the list(say list1) what function do we use ?
a) list1.shuffle()
b) shuffle(list1)
c) random.shuffle(list1)
d) random.shuffleList(list1)
Answer:c
Explanation:Execute in the shell to verify .
8. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct (multiple
answers allowed) ?
a) print(list1[0])
b) print(list1[:2])
c) print(list1[:-2])
d) print(list1[4:6])
Answer:a, b, c, d
Explanation:Slicing is allowed in lists just as in the case of strings.
9. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?
a) Error
b) None
c) 25
d) 2
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.
This set of Python Questions & Answers focuses on Lists.
1. What is the output when following code is executed ?
>>>names = ['Amir', 'Bear', 'Charlton', 'Daman']
>>>print names[-1][-1]
a) A
b) Daman
c) Error
d) n
Answer:d
Answer:b
Explanation:Elements are compared one by one.
6. To add a new element to a list we use which command ?
a) list1.add(5)
b) list1.append(5)
c) list1.addLast(5)
d) list1.addEnd(5)
Answer:b
Explanation:We use the function append to add an element to the list.
7. To insert 5 to the third position in list1, we use which command ?
a) list1.insert(3, 5)
b) list1.insert(2, 5)
c) list1.add(3, 5)
d) list1.append(3, 5)
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.
9. Suppose list1 is [3, 4, 5, 20, 5], what is list1.index(5) ?
a) 0
b) 1
c) 4
d) 2
Answer:d
Explanation:Execute help(list.index) to get details.
10. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.count(5) ?
a) 0
b) 4
c) 1
d) 2
Answer:d
Explanation:Execute in the shell to verify.
This set of Python Questions & Answers focuses on Lists.
1. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.reverse() ?
a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [25, 20, 5, 5, 4, 3, 3, 1]
d) [3, 1, 25, 5, 20, 5, 4, 3]
Answer:d
Explanation:Execute in the shell to verify.
d) 12
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.
6. What will be the output?
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
print len(list1 + list2)
a) 2
b) 4
c) 5
d) 8
View Answer
Answer:d
Explanation:+ appends all the elements individually into a new list.
7. What will be the output?
def addItem(listParam):
listParam += [1]
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.
8. What will be the output?
def increment_items(L, increment):
i=0
while i < len(L):
L[i] = L[i] + increment
i=i+1
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.
9. What will be the output?
def example(L):
''' (list) -> list
'''
i=0
result = []
while i < len(L):
result.append(L[i])
i=i+3
return result
a) Return a list containing every third item from L starting at index 0.
b) Return an empty list
c) Return a list containing every third index from L starting at index 0.
d) Return a list containing the items from L starting from index 0, omitting every third item.
Answer:a
Explanation:Run the code to get a better understanding with many arguements.
10. What will be the output?
veggies = ['carrot', 'broccoli', 'potato', 'asparagus']
veggies.insert(veggies.index('broccoli'), 'celery')
print(veggies)
a) ['carrot', 'celery', 'broccoli', 'potato', 'asparagus']
b) ['carrot', 'celery', 'potato', 'asparagus']
c) ['carrot', 'broccoli', 'celery', 'potato', 'asparagus']
d) ['celery', 'carrot', 'broccoli', 'potato', 'asparagus']
Answer:a
Explanation:Execute in the shell to verify.
Correct
1.00
c) 16
d) 32
Answer:c
Explanation:Execute in the shell to verify.
3. What will be the output?
values = [[3, 4, 5, 1], [33, 6, 1, 2]]
v = values[0][0]
for row in range(0, len(values)):
for column in range(0, len(values[row])):
if v < values[row][column]:
v = values[row][column]
print(v)
a) 3
b) 5
c) 6
d) 33
Answer:d
Explanation:Execute in the shell to verify.
4. What will be the output?
values = [[3, 4, 5, 1], [33, 6, 1, 2]]
v = values[0][0]
for lst in values:
for element in lst:
if v > element:
v = element
print(v)
a) 1
b) 3
c) 5
d) 6
Answer:a
Explanation:Execute in the shell to verify.
5. What will be the output?
values = [[3, 4, 5, 1 ], [33, 6, 1, 2]]
for row in values:
row.sort()
for element in row:
print(element, end = " ")
print()
a) The program prints two rows 3 4 5 1 followed by 33 6 1 2
b) The program prints on row 3 4 5 1 33 6 1 2
c) The program prints two rows 3 4 5 1 followed by 33 6 1 2
d) The program prints two rows 1 3 4 5 followed by 1 2 6 33
Answer:d
Explanation:Execute in the shell to verify.
6. What is the output?
a) 1
b) 2
c) 4
d) 5
Answer:c
Explanation:Execute in the shell to verify.
10. What will be the output?
points = [[1, 2], [3, 1.5], [0.5, 0.5]]
points.sort()
print(points)
a) [[1, 2], [3, 1.5], [0.5, 0.5]]
b) [[3, 1.5], [1, 2], [0.5, 0.5]]
c) [[0.5, 0.5], [1, 2], [3, 1.5]]
d) [[0.5, 0.5], [3, 1.5], [1, 2]]
Answer:c
Explanation:Execute in the shell to verify.
This set of Python Questions & Answers focuses on Dictionaries.
1. Which of the following statements create a dictionary?(multiple answers
allowed)
a) d = {}
b) d = {john:40, peter:45}
c) d = {40:john, 45:peter}
d) d = (40:john, 45:peter)
Answer:a,b,c
Explanation:Dictionaries are created by specifying keys and values
2. What are the keys?
d = {"john":40, "peter":45}
a) john, 40, 45, and peter
b) john and peter
c) 40 and 45
d) d = (40:john, 45:peter)
Answer:b
Explanation:Dictionaries appear in the form of keys and values.
3. What will be the output?
d = {"john":40, "peter":45}
"john" in d
a) True
b) False
c) None
d) Error
Answer:a
Explanation:In can be used to check if the key is int dictionary.
4. What will be the output?
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 == d2
a) True
b) False
c) None
d) Error
Answer:b
Explanation:If d2 was initialized as d2 = d1 the answer would be true.
5. What will be the output?
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 > d2
a) True
b) False
c) Error
d) None
Answer:c
Explanation:Arithmetic > operator cannot be used with dictionaries.
6. What is the output?
d = {"john":40, "peter":45}
d["john"]
a) 40
b) 45
c) john
d) peter
Answer:a
Explanation:Execute in the shell to verify.
7. Suppose d = {john:40, peter:45}, to delete the entry for john what
command do we use
a) d.delete(john:40)
b) d.delete(john)
c) del d["john"]
d) del d(john:40)
View Answer
Answer:c
Explanation:Execute in the shell to verify.
8. Suppose d = {john:40, peter:45}, to obtain the number of entries in
dictionary what command do we use
a) d.size()
b) len(d)
c) size(d)
d) d.len()
Answer:b
Explanation:Execute in the shell to verify.
9. What will be the output?
d = {"john":40, "peter":45}
print(list(d.keys()))
a) ["john", "peter"]
b) ["john":40, "peter":45]
c) (john, peter)
d) (john:40, peter:45)
Answer:a
Explanation:Execute in the shell to verify.
10. Suppose d = {john:40, peter:45}, what happens when retieving a value
using d["susan"]?
a) Since susan is not a value in the set, Python raises a KeyError exception.
b) It is executed fine and no exception is raised, and it returns None.
c) Since susan is not a key in the set, Python raises a KeyError exception.
d) Since susan is not a key in the set, Python raises a syntax error.
Answer:c
Explanation:Execute in the shell to verify.
This set of Python Questions & Answers focuses on tuples.
1. Which of the following is a Python tuple?
a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}
Answer:b
Explanation:Tuples are characterised by their round brackets.
2. Suppose t = (1, 2, 4, 3), which of the following is incorrect?
a) print(t[3])
b) t[3] = 45
c) print(max(t))
d) print(len(t))
View Answer
Answer:b
Explanation:Values cannot be modified in the case of tuple.
3. What will be the output?
>>>t=(1,2,4,3)
>>>t[1:3]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
Answer:c
Explanation:Slicing just as in the case of strings takes place in tuples.
4. What will be the output?
>>>t=(1,2,4,3)
>>>t[1:-1]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
Answer:c
Explanation:Slicing just as in the case of strings takes place in tuples.
c) When you open a file for writing, if the file does not exist, a new file is created.
d) When you open a file for writing, if the file exists, the existing file is overwritten with the
new file.
Answer:a,c,d.
Explanation:The program will throw an error.
5. To read two characters from a file object infile, we use
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
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.
7. What is the output?
f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break
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.
10. The readlines() method returns
a) str
b) a list of lines
c) a list of single characters
d) a list of integers
Answer:b
Explanation:Every line is stored in a list and returned.
This section on Python aptitude questions and answers focuses on Function 2.
1. Which are the advantages of functions in python?
a) Reducing duplication of code
b) Decomposing complex problems into simpler pieces
c) Improving clarity of the code
d) Reuse of code
e) Information hiding
f) All of the mentioned
Answer: f
Explanation: None.
2. What are the two types of functions?
a) Custom function
b) Built-in function
c) User-Defined function
d) System function
Answer: b and c
Explanation: Built-in functions and user defined ones. The built-in functions are part of the
Python language. Examples are: dir(), len() or abs(). The user defined functions are functions
created with the def keyword.
3. Where is function defined?
a) Module
b) Class
c) Another function
d) None of the mentioned
Answer: a, b and c
Explanation: Functions can be defined inside a module, a class or another function.
4. What is called when a function is defined inside a class?
a) Module
b) Class
c) Another function
d) Method
Answer: d
Explanation: None.
5. Which of the following is the use of id() function in python?
Answer: a
Explanation: None.
9. What is the output of the below program?
def power(x, y=2):
r=1
for i in range(y):
r=r*x
return r
print power(3)
print power(3, 3)
a) 212
32
b) 9
27
c) 567
98
d) None of the mentioned
View Answer
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.
10. What is the output of the below program?
def sum(*args):
'''Function returns the sum
of all values'''
r=0
for i in args:
r += i
return r
print sum.__doc__
print sum(1, 2, 3)
print sum(1, 2, 3, 4, 5)
a) 6
15
b) 6
100
c) 123
12345
d) None of the mentioned
View Answer
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.
5. Lambda is a statement.
a) True
b) False
Answer: b
Explanation: None.
6. Lambda contains block of statements
a) True
b) False
View Answer
Answer: b
Explanation: None.
7. What is the output of below program?
def f(x, y, z): return x + y + z
f(2, 30, 400)
a) 432
b) 24000
c) 430
d) None of the mentioned
Answer: a
Explanation: None.
8.What is the output of below program?
def writer():
title = 'Sir'
name = (lambda x:title + ' ' + x)
return name
who = writer()
who('Arthur')
a) Arthur Sir
b) Sir Arthur
c) Arthur
d) None of the mentioned
Answer: b
Explanation: None.
9. What is the output of this program?
L = [lambda x: x ** 2,
lambda x: x ** 3,
lambda x: x ** 4]
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.
10. What is the output of this program?
min = (lambda x, y: x if x < y else y)
min(101*99, 102*98)
a) 9997
b) 9999
c) 9996
d) None of the mentioned
Answer: c
Explanation: None.
Below are top 20 Python interview questions, frequently asked to fresher and
amateur Python programmers.
1. Is python compiled based or interpretive based language?
Python mostly used in scripting, is general purpose programming language which supports
OOP Object oriented programming principles as supported by C++, Java, etc.
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.
2. What built-in type does python provide?
Following are the most commonly used built-in types provided by Python:
Immutable built-in types of python
Numbers
Strings
Tuples
Mutable built-in types of python
List
Dictionaries
Sets
3. What is module in python?
Modules are way to structure python program. A module would have set of related
functionalities. Each python program file (.py file) is a module, which imports other modules
(object) to use names (attributes) they define
using object.attribute notation. All the top level names of a module are attributes, exported
for use by the importer of this module.
Filename of a module turns out to be an object name where it is imported.
import re; statement imports all the names defined in module re.
from statements can be used to import specific names from a module.
Both the above statements finds, compiles and loads (if not yet loaded) the module.
Python by default imports modules only once per file per process, when the very first import
statement is encountered.
With from statement, names can be directly used. module name is not required.
4. What is package in python?
A folder of python programs (modules) is a package of modules. A package can have
subfolders and modules.
A import statement can import packages and each import package introduces a namespace.
import folder1.subfolder2.module1
OR
from folder1.subfolder2.module1 import names
To import a package, __init__.py file must be present in each of the folders, subfolders.
5. What is namespace in python?
Every name introduced in a python program has a place where it lives and can be looked for.
This is its namespace. Consider it as a box where a variable name mapped to object is
placed. Whenever the variable name is referenced, this box is looked out to get
corresponding object.
For example, functions defined using def have namespace of the module in which it is
defined. And so 2 modules can define function with same name.
Modules and namespace go hand in hand. Each module introduces a namespace.
Namespace helps in reusing name by avoiding name collision. Classes and functions are
other namespace constructs.
6. What is scope in python?
Scope for names introduced in a python program is a region where it could be used, without
any qualification. That is, scope is region where the unqalified reference to a name can be
looked out in the namespace to find the
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):
...
temp=x+y
...
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
7. What are the different ways of passing arguments to a function in python?
Different forms of calling function and passing arguments to functions in python:
Function definition
Function Caller
Function call mapping to function definition
def func(x,y) func(a,b)
Positional matching of argument
func(y=b, x=a)
Argument name matching
def func(x,y=10)
func(a)
func(a,b)
Default value for argument
def func(x,y, *tuple_arg)
func(a,b)
func(a,b,c) and many other arguments can be passed as positional arguments
Function with varying positional arguments stored in a tuple
Example:
def add(x,y, *tup):
temp = x+y
for elem in tup:
temp = temp + elem
return temp
print add(1,2) # prints 3
print add(1,2,3,4) # prints 10
def func(x,y, **dict_arg)
func(a,b)
func(a,b, c=10)
func(a,b, c=10, name='abcd' ) and many other arguments can be passed as keyword
argument
Function with varying keyword arguments stored in dictionary.
Example:
def percentage(mks1, mks2, **dict):
total_mks = mks1 + mks2
return total_mks / float( dict['out_of'] )
print percentage(65, 50, out_of=150)
8. What is lambda in python?
lamda is a single expression anonymous function often used as inline function. It takes
general form as:
lambda arg1 arg2 ... : expression where args can be used
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']]
10. How exceptions are handle in python?
Exceptions are raised by Python when some error is detected at run time. Exceptions can be
caught in the program using try and except statments. Once the exceptions is caught, it can
be corrected in the program to avoid abnormal termination. Exceptions caught inside a
function can be transferred to the caller to handle it. This is done by rethrowing exception
using raise. Python also provide statements to be grouped inside finally which are executed
irrespective of exception thrown from within try .
Example of handling exception and rethrowing exception:
def func2(a,b):
try:
temp = a/float(b)
except ZeroDivisionError:
print "Exception caught. Why is b = 0? Rethrowing. Please handle"
raise ZeroDivisionError
finally:
print "Always executed"
def func1():
a=1
b=1
print "Attempt 1: a="+str(a)+", b="+str(b)
func2(a,b)
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
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.
Example of iterator on list:
>>> a=[1,2,3]
>>> i1= a.__iter__() # creating an iterator using __iter__() on container
>>> i1
<listiterator object at 0x7f5192ccbd10>
>>> i2= iter(a)
# creating another iterator using iter() which calls __iter__() on
container
>>> i2
<listiterator object at 0x7f5192ccbcd0>
>>> i1.next()
1
>>> next(i1)
# calls i1.next()
2
>>> next(i2)
1
Iterators are required to implement __iter__ which returns the iterator (self) . Hence it can be
used with for in
>>> for x in i1:
... print x
...
3
16. What are generators in Python?
Generators are way of implementing iterators. Generator function is a normal function
except that it contains yield expression in the function definition making it a generator
function. This function returns a generator
iterator known as generator. To get the next value from a generator, we use the same builtin 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
17. How do you perform unit testing in Python?
Python provides a unit tesing framework called unittest . unittest module supports
automation testing, sharing of setup and shutdown code for tests, aggregation of tests into
collections, and independence of the tests from the reporting framework.
...
<last statement >
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.
Python supports limited form of multiple inheritance as:
class DeriveClass( BaseClass1, BaseClass2, ...):
<statement 1>
<statement 2>
...
<last statement >
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.
-Build-in Data Structure: contains lots of data structure like lists, numbers & dictionaries.
2. Define a method in Python?
A function on object x is a method which is called as x.name(arguments). Inside the
definition of class, methods are defined as functions:
class C:
def meth(self, atg):
return arg*2+self.attribute
3. Define self?
'self' is a conventional name of methods 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).
4. Describe python usage in web programming?
Python is used perfectly for web programming and have many special features to make it
easy to use. Web frame works, content management systems, WebServers, CGI scripts,
Webclient programming, Webservices, etc are the
features supported by python. Python language is used to create various high end
applications because of its flexibility.
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.
6. Rules for local and global variables in python?
In python, the variables referenced inside a function are global. When a variable is assigned
new value anywhere in the body of a function then it is assumed as local. In a function, if a
variable ever assigned new value then
the variable is implicitly local and explicitly it should be declared as global. If all global
references require global then you will be using global at anytime. Youd declare as global
each reference to built-in function or to component of module which is imported. The
usefulness of global declaration in identifying side-effects is defeated by this clutter.
7. How to find methods or attributes of an object?
Built-in dir() function of Python ,on an instance shows the instance variables as well as the
methods and class attributes defined by the instances class and all its base classes
alphabetically. So by any object as argument
to dir() we can find all the methods & attributes of the objects class.
Following code snippet shows dir() at work :
class Employee:
def __init__(self,name,empCode,pay):
self.name=name
self.empCode=empCode
self.pay=pay
print("dir() listing all the Methods & attributes of class Employee")
print dir(e)
----------------------------------------------------Output
dir() listing all the Methods & attributes of class Employee
Gather the arguments using the * and ** specifiers in the functions 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
another function by using * and **:
def fun1(a, *tup, **keywordArg):
...
keywordArg['width']='23.3c'
...
Fun2(a, *tup, **keywordArg)
14. Explain pickling and unpickling.
Pickle is a standard module which serializes & de-serializes a python object structure. Pickle
module accepts any python object converts it into a string representation & dumps it into a
file(by using dump() function) which
can be used later, process is called pickling. Whereas unpickling is process of retrieving
original python object from the stored string representation for use.
15. Explain how python is interpreted.
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.
16. How is memory managed in python?
Memory management in Python involves a private heap containing all Python objects and
data structures. Interpreter takes care of Python heap and that the programmer has no
access to it. The allocation of heap space for Python objects is done by Python memory
manager. The core API of Python provides some tools for the programmer to code reliable
and more robust program. Python also has a build-in garbage collector which recycles all the
unused memory. When an object is no longer referenced by the program, the heap space it
occupies can be freed. The garbage collector determines objects which are no longer
referenced by the sprogram frees the occupied memory and make it available to the heap
space. The gc module defines functions to enable /disable
garbage collector:
gc.enable() -Enables automatic garbage collection.
gc.disable() - Disables automatic garbage collection.
17. Explain indexing and slicing operation in sequences
Different types of sequences in python are strings, Unicode strings, lists, tuples, buffers, and
xrange objects. Slicing & indexing operations are salient features of sequence. indexing
operation allows to access a particular
item in the sequence directly ( similar to the array/list indexing) and the slicing operation
allows to retrieve a part of the sequence. The slicing operation is used by specifying the
name of the sequence followed by an
optional pair of numbers separated by a colon within square brackets say S[startno.:stopno].
The startno in the slicing operation indicates the position from where the slice starts and the
stopno indicates where the slice
will stop at. If the startno is ommited, Python will start at the beginning of the sequence. If
the stopno is ommited, Python will stop at the end of the sequence..
Following code will further explain indexing & slicing operation:
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.
29. Why is not all memory freed when Python exits?
Objects referenced from the global namespaces of Python modules are not always deallocated 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.
30. What is a Lambda form? Explain about assert statement?
The lambda form:
Using lambda keyword tiny anonymous functions can be created. It is a very powerful
feature of Python which declares a one-line unknown small function on the fly. The lambda is
used to create new function objects and then
return them at run-time. The general format for lambda form is:
lambda parameter(s): expression using the parameter(s)
For instance k is lambda function>>> k= lambda y: y + y
>>> k(30)
60
>>> k(40)
80
The assert statement:
The build-in assert statement of python introduced in version 1.5 is used to assert that
something is true. Programmers often place assertions at the beginning of a function to
check for valid input, and after function call
to check for valid output. Assert statement can be removed after testing of program is over.
If assert evaluates to be false, an AssertionError exception is raised. AssertionError
exceptions can be handled with the try-except
statement.
The general syntax for assert statement is:
assert Expression[, Arguments]
31. Explain the role of repr function.
Python can convert any value to a string by making use of two functions repr() or str(). The
str() function returns representations of values which are human-readable, while repr()
generates representations which can be read
by the interpreter. repr() returns a machine-readable representation of values, suitable for
an exec command. Following code sniipets shows working of repr() & str() :
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
32. What is LIST comprehensions features of Python used for?
LIST comprehensions features were introduced in Python version 2.0, it creates a new list
based on existing list. It maps a list into another list by applying a function to each of the
elements of the existing list. List
comprehensions creates lists without using map() , filter() or lambda form.
33. How do you make a higher order function in Python?
A higher-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 , we need to
import functools module The
functools.partial() function is used often for high order function.
34. Explain how to copy an object in Python.
There are two ways in which objects can be copied in python. Shallow copy & Deep copy.
Shallow copies duplicate as minute as possible whereas Deep copies duplicate everything. If
a is object to be copied then
-copy.copy(a) returns a shallow copy of a.
-copy.deepcopy(a) returns a deep copy of a.
35. How do I convert a string to a number?
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
36. What is a negative index in python?
Python arrays & list items can be accessed with positive or negative numbers (also known as
index). For instance our array/list is of size n, then for positive index 0 is the first index, 1
second, last index will be n-1. For
negative index, -n is the first index, -(n-1) second, last negative index will be 1. A negative
index accesses elements from the end of the list counting backwards.
self.pay=pay
e1 = Employee("Sarah",99,30000.00)
e2 = Employee("Asrar",100,60000.00)
print("Employee Details:")
print(" Name:",e1.name,"Code:", e1.empCode,"Pay:", e1.pay)
print(" Name:",e2.name,"Code:", e2.empCode,"Pay:", e2.pay)
--------------------------------------------------------------Output
Employee Details:
(' Name:', 'Sarah', 'Code:', 99, 'Pay:', 30000.0)
(' Name:', 'Asrar', 'Code:', 100, 'Pay:', 60000.0)
40. Describe how to send mail from a Python script.
The smtplib module defines an SMTP client session object that can be used to send mail to
any Internet machine.
A sample email is demonstrated below.
import smtplib
SERVER = smtplib.SMTP(smtp.server.domain)
FROM = sender@mail.com
TO = ["user@mail.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Main message
message = """
From: Sarah Naaz < sender@mail.com >
To: CarreerRide user@mail.com
Subject: SMTP email msg
This is a test email. Acknowledge the email by responding.
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
41. Describe how to generate random numbers in Python.
Thee standard module random implements a random number generator.\
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, b].
random()returns a floating point number in the range [0, 1].
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)
__________
51. What is the language from which Python has got its features or derived its
features?
Most of the object oriented programming languages to name a few are C++, CLISP and Java
is the language from which Python has got its features or derived its features.
52. What are the disadvantages of the Python programming language?
One of the disadvantages of the Python programming language is it is not suited for fast and
memory intensive tasks.
53. Why is not all memory freed when Python exits?
Objects referenced from the global namespaces of Python modules are not always deallocated 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.
54. Which of the languages does Python resemble in its class syntax?
C++ is the appropriate language that Python resemble in its class syntax.
55. Who created the Python programming language?
Python programming language was created by Guido van Rossum.
=======================================================
===
1 line: Output
print 'Hello, world!'
2 lines: Input, assignment
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
3 lines: For loop, built-in enumerate function, new style formatting
friends = ['john', 'pat', 'gary', 'michael']
for i, name in enumerate(friends):
print "iteration {iteration} is {name}".format(iteration=i, name=name)
4 lines: Fibonacci, tuple assignment
parents, babies = (1, 1)
while babies < 100:
print 'This generation has {0} babies'.format(babies)
parents, babies = (babies, parents + babies)
5 lines: Functions
def greet(name):
print 'Hello', name
greet('Jack')
greet('Jill')
greet('Bob')
6 lines: Import, regular expressions
import re
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
20 lines: Prime numbers sieve w/fancy generators
import itertools
def iter_primes():
# an iterator of all numbers between 2 and +infinity
numbers = itertools.count(2)
# generate primes forever
while True:
# get the first number from the iterator (always a prime)
prime = numbers.next()
yield prime
# this code iteratively builds up a chain of
# filters...slightly tricky, but ponder it a bit
numbers = itertools.ifilter(prime.__rmod__, numbers)
for p in iter_primes():
if p > 1000:
break
print p
21 lines: XML/HTML parsing (using Python 2.5 or third-party library)
dinner_recipe = '''<html><body><table>
<tr><th>amt</th><th>unit</th><th>item</th></tr>
<tr><td>24</td><td>slices</td><td>baguette</td></tr>
<tr><td>2+</td><td>tbsp</td><td>olive oil</td></tr>
<tr><td>1</td><td>cup</td><td>tomatoes</td></tr>
<tr><td>1</td><td>jar</td><td>pesto</td></tr>
</table></body></html>'''
# In Python 2.5 or from http://effbot.org/zone/element-index.htm
import xml.etree.ElementTree as etree
tree = etree.fromstring(dinner_recipe)
# For invalid HTML use http://effbot.org/zone/element-soup.htm
# import ElementSoup, StringIO
# tree = ElementSoup.parse(StringIO.StringIO(dinner_recipe))
pantry = set(['olive oil', 'pesto'])
for ingredient in tree.getiterator('tr'):
amt, unit, item = ingredient
if item.tag == "td" and item.text not in pantry:
print "%s: %s %s" % (item.text, amt.text, unit.text)
28 lines: 8-Queens Problem (define your own exceptions)
BOARD_SIZE = 8
class BailOut(Exception):
pass
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)
33 lines: "Guess the Number" Game (edited) from http://inventwithpython.com
import random
guesses_made = 0
name = raw_input('Hello! What is your name?\n')
number = random.randint(1, 20)
print 'Well, {0}, I am thinking of a number between 1 and 20.'.format(name)
while guesses_made < 6:
guess = int(raw_input('Take a guess: '))
guesses_made += 1
if guess < number:
print 'Your guess is too low.'
if guess > number:
print 'Your guess is too high.'
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)
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print i, a[i]
#! python
# break operator
# prime numbers
for n in range(2, 1000):
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is a prime number'
#! 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
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.
print word[:2]
print word[2:]
# 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:
print 'x' + word[1:]
print 'Splat' + word[4]
# error
#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
# raw input of strings only!
st = raw_input("")
print st
st=st*3 # triple the string
print st
#! 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
print
print
print
a*a
a*b
a.real
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
# list indices start at 0,
print 'a[0]=', a[0]
print 'a[3]=', a[3]
print 'a[-2]=', a[-2]
# lists can be sliced, concatenated and so on:
print "a[1:-1]=", a[1:-1]
print a[:2] + ['bacon', 2*2]
print 3*a[:3] + ['Boe!']
# possible to change individual elements of a list:
a[2] = a[2] + 23
print "changing a[2]=", 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
a[:0] = a
print a
print t
(12345, 54321, 'hello!')
# Tuples may be nested:
u = t, (1, 2, 3, 4, 5)
print u
# ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
#! 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
# The dict() constructor builds dictionaries directly from lists
# of key-value pairs stored as tuples. When the pairs form a pattern,
# list comprehensions can compactly specify the key-value list.
d=dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
print d
vec=[1,2,3,4,5]
dd=dict([(x, x**2) for x in vec])
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
#! 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']
s=re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
print s # 'cat in the hat'
#! python
#! 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()
# work with files
#open file for write
f=open('c:/TEMP/workpy.txt','w')
print f
f.write("aaaaaaaaaaaaaaaaaaa\n")
f.write("bbbbbbbbbbbbbb");
# work with files
#open file for read
f=open('c:/TEMP/workpy.txt','r')
# line reading
s=f.readline()
print s
f.close()
# work with files
#open file for read
f=open('c:/TEMP/workpy.txt','r')
# pieces reading
s1=f.read(5)
print s1
s2=f.read(19)
print s2
s2=f.read(25)
print s2
f.close()
# work with files
#open file for read
f=open('c:/TEMP/workpy.txt','r')
# 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()
# work with files
# seek
f=open('c:/TEMP/workpy.txt','r+')
f.write('0123456789abcdef')
f.seek(5)
# Go to the 6th byte in the file
print f.read(1)
f.seek(-3, 2) # Go to the 3rd byte before the end
print f.read(1)
#! 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']