Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Python interview Questions, Exams of Information Technology

Here are python interview questions asked for data science jobs.

Typology: Exams

2019/2020

Uploaded on 12/16/2020

heena-mansoori
heena-mansoori 🇺🇸

1 document

1 / 89

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Top 25 Python Questions:
1) What is Python? What are the benefits of using Python?
Python is a programming language with objects, modules, threads, exceptions and automatic
memory management. The benefits of pythons are that it is simple and easy, portable,
extensible, build-in data structure and it is an open source.
2) What is PEP 8?
PEP 8 is a coding convention, a set of recommendation, about how to write your Python code
more readable.
3) What is pickling and unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps
it into a file by using dump function, this process is called pickling. While the process of
retrieving original Python objects from the stored string representation is called unpickling.
4) How Python is interpreted?
Python language is an interpreted language. Python program runs directly from the source
code. It converts the source code that is written by the programmer into an intermediate
language, which is again translated into machine language that has to be executed.
5) How memory is managed in Python?
Python memory is managed by Python private heap space. All Python objects and data
structures are located in a private heap. The programmer does not have an access to
this private heap and interpreter takes care of this Python private heap.
The allocation of Python heap space for Python objects is done by Python memory
manager. The core API gives access to some tools for the programmer to code.
Python also have an inbuilt garbage collector, which recycle all the unused memory and
frees the memory and makes it available to the heap space.
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.
7) What are Python decorators?
A Python decorator is a specific change that we make in Python syntax to alter functions easily.
8) What is the difference between list and tuple?
The difference between list and tuple is that list is mutable while tuple is not. Tuple can be
hashed for e.g as a key for dictionaries.
9) How are arguments passed by value or by reference?
Everything in Python is an object and all variables hold references to the objects. The
references values are according to the functions; as a result you cannot change the value of the
references. However, you can change the objects if it is mutable.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59

Partial preview of the text

Download Python interview Questions and more Exams Information Technology in PDF only on Docsity!

Top 25 Python Questions:

  1. What is Python? What are the benefits of using Python? Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.
  2. What is PEP 8? PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.
  3. What is pickling and unpickling? Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
  4. How Python is interpreted? Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
  5. How memory is managed in Python? Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap. The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code. Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.
  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.
  7. What are Python decorators? A Python decorator is a specific change that we make in Python syntax to alter functions easily.
  8. What is the difference between list and tuple? The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.
  9. How are arguments passed by value or by reference? Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.
  1. What is Dict and List comprehensions are? They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.
  2. 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
  3. 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.
  4. What is lambda in Python? It is a single expression anonymous function often used as inline function.
  5. 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.
  6. 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.
  7. In Python what are iterators? In Python, iterators are used to iterate a group of elements, containers like list.
  8. 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.
  9. 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.
  10. 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.

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 = fun2() print 'b outside fun2', b


Output $ python variable_localglobal.py a: 100 local a: 33 a outside fun1: 100 b : global b: 33 b outside fun2: 33

  1. 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= b= c= module1.py: import config

config.a = 1 config.b = config.c= print “ a, b & resp. are : “ , config.a, config.b, config.c


output of module1.py will be 1 2 3

  1. 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.
  2. 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)

('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

  1. Explain the disadvantages of python. Disadvantages of Python are: Python isn't the best for memory intensive tasks. Python is interpreted language & is slow compared to C/C++ or java. Python not a great choice for a high-graphic 3d game that takes up a lot of CPU. Python is evolving continuously, with constant evolution there is little substantial documentation available for the language. This set of Python Questions & Answers focuses on “Core Data Types”. 1. Which of these in not a core datatype? a) Lists b) Dictionary c) Tuples d) Class Answer:d Explanation:Class is a user defined datatype.
  1. 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.
  2. 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.

  1. Which of the following will run without errors(multiple answers possible)? a) round(45.8) b) round(6352.898,2) c) round() d) round(7463.123,2,1) Answer:a,b Explanation:Execute help(round) in the shell to get details of the parameters that are passed into the round function.
  2. What is the return type of function id? a) int b) float c) bool d) dict Answer:a Explanation:Execute help(id) to find out details in python shell.id returns a integer value that is unique.
  3. 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)

Answer:d Explanation:Dictionary stores values in terms of keys and values.

  1. 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) ”’That’s okay”’ Answer:b,c Explanation:Carefully look at the colons.
  2. 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.
  3. What is the average value of the code that is executed below?

grade1 = 80 grade2 = 90 average = (grade1 + grade2) / 2 a) 85 b) 85. c) 95 d) 95. Answer:b Explanation:Cause a decimal value to appear as output.

  1. 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.

  1. 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. This set of Python Questions & Answers focuses on “Strings”.
  2. What is the output when following statement is executed?

"a"+"bc" a) a b) bc c) bca d) abc Answer:d Explanation:+ operator is concatenation operator.

  1. What is the output when following statement is executed?

"abcd"[2:] a) a b) ab c) cd d) dc Answer:c Explanation:Slice operation is performed on string.

  1. The output of executing string.ascii_letters can also be achieved by: a) string.ascii_lowercase_string.digits b) string.ascii_lowercase+string.ascii_upercase c) string.letters d) string.lowercase_string.upercase

Explanation:String literals seperated by white space are allowed. They are concatenated.

  1. What is the output when following statement is executed?

print '\x97\x98' a) Error b) 97 98 c) _~ d) \x97\x Answer:c Explanation:\x is an escape sequence that means the following 2 digits are a hexadicmal number encoding a character.

  1. What is the output when following code is executed?

str1="helloworld" str1[::-1] a) dlrowolleh

b) hello c) world d) helloworld Answer:a Explanation:Execute in shell to verify.

  1. print 0xA + 0xB + 0xC : a) 0xA0xB0xC b) Error c) 0× 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”.
  2. 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.

  1. 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.

  1. 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.

  1. What is the output of the following code?

example = "snow world" example[3] = 's' print example

str1="helloworld" >>>str1[::-1] a) dlrowolleh b) hello c) world d) helloworld Answer:a Explanation:Execute in shell to verify. 10. print 0xA + 0xB + 0xC : a) 0xA0xB0xC b) Error c) 0× 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. 4. What is the output of the following code? >>>example = "snow world" >>>example[3] = 's' >>>print example a) snow b) snow world str1[::-1] a) dlrowolleh b) hello c) world d) helloworld Answer:a Explanation:Execute in shell to verify. 10. print 0xA + 0xB + 0xC : a) 0xA0xB0xC b) Error c) 0× 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. 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.

d) None Answer:b Explanation:Starts with checks if the given string starts with the parameter that is passed.

  1. To concatenate two strings to a third what statements are applicable (multiple answers are allowed)? a) s3 = s1 + s b) s3 = s1.add(s2) c) s3 = s1.add(s2) d) s3 = s1 * s Answer:a,c Explanation:add is another method that can be used for concatenation. This set of Python Questions & Answers focuses on “Strings”.
  2. 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.

  1. 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.

  1. 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.
  2. 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.

  1. 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) hello b) hello c) Error d) hello Answer:c Explanation:Cannot concantenate str and int objects.
  2. 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.

  1. 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. b) Welcome#111#924. c) Welcome#111#. d) Welcome # 111#924. Answer:d

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.

  1. To check whether string s1 contains s2, use a) s1.contains(s2) b) s1 in s 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.
  2. 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.
  3. 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.

  1. 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.
  2. 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.
  3. Suppose x is 345.3546, what is format(x, “10.3f”) (_ indicates space) a) __345. b) ___345. c) ____345. d) _____345. Answer:b Explanation:Execute in the shell to verify. This set of Python Questions & Answers focuses on “Lists”.
  4. Which of the following commands will create a list(multiple answers allowed)? a) list1 = list() b) list1 = [] c) list1 = list([1, 2, 3]) d) list1 = [1, 2, 3]