Wednesday 25 April 2018

Python Interview Question

1. What are the key features of Python?
If it makes for an introductory language to programming, Python must mean something. These are its qualities:
  1. Interpreted
  2. Dynamically-typed
  3. Object-oriented
  4. Concise and simple
  5. Free
  6. Has a large community


In fact, that isn’t all. Python is so much more.
2. Differentiate between lists and tuples.
The major difference is that a list is mutable, but a tuple is immutable. Examples:
  1. >>> mylist=[1,3,3]
  2. >>> mylist[1]=2
  3. >>> mytuple=(1,3,3)
  4. >>> mytuple[1]=2
  5. Traceback (most recent call last):
  6. File "<pyshell#97>", line 1, in <module>
  7. mytuple[1]=2
TypeError: ‘tuple’ object does not support item assignment
For more insight, refer to Tuples vs Lists.
Q.4 to Q.20 are some basic Python Interview question for freshers, however Experience can also refer these questions to revise basic concepts.
3. Explain the ternary operator in Python.
Unlike C++, we don’t have ?: in Python, but we have this:
[on true] if [expression] else [on false]
If the expression is True, the statement under [on true] is executed. Else, that under [on false] is executed.
Below is how you would use it:

  1. >>> a,b=2,3
  2. >>> min=a if a<b else b
  3. >>> min
2
  1. >>> print("Hi") if a<b else print("Bye")
Hi
4. How is multithreading achieved in Python?
A thread is a lightweight process, and multithreading allows us to execute multiple threads at once. As you know, Python is a multithreaded language. It has a multi-threading package.
The GIL (Global Interpreter Lock) ensures that a single thread executes at a time. A thread holds the GIL and does a little work before passing it on to the next thread. This makes for an illusion of parallel execution. But in reality, it is just threads taking turns at the CPU. Of course, all the passing around adds overhead to the execution.
5. Explain inheritance.
When one class inherits from another, it is said to be the child/derived/sub class inheriting from the parent/base/super class. It inherits/gains all members (attributes and methods).
Inheritance lets us reuse our code, and also makes it easier to create and maintain applications. Python supports the following kinds of inheritance:
  1. Single Inheritance- A class inherits from a single base class.
  2. Multiple Inheritance- A class inherits from multiple base classes.
  3. Multilevel Inheritance- A class inherits from a base class, which, in turn, inherits from another base class.
  4. Hierarchical Inheritance- Multiple classes inherit from a single base class.
  5. Hybrid Inheritance- Hybrid inheritance is a combination of two or more types of inheritance.
6. What is Flask?
Flask, as we’ve previously discussed, is a web microframework for Python. It is based on the ‘Werkzeug, Jinja 2 and good intentions’ BSD license. Two of its dependencies are Werkzeug and Jinja2. This means it has around no dependencies on external libraries. Due to this, we can call it a light framework.
A session uses a signed cookie to allow for the user to look at and modify session contents. It will remember information from one request to another. However, to modify a session, the user must have the secret key Flask.secret_key.
7. How is memory managed in Python?
Python has a private heap space to hold all objects and data structures. Being programmers, we cannot access it; it is the interpreter that manages it. But with the core API, we can access some tools. The Python memory manager controls the allocation.
Additionally, an inbuilt garbage collector recycles all unused memory so it can make it available to the heap space.
8. Explain help() and dir() functions in Python.
The help() function displays the documentation string and help for its argument.
  1. >>> import copy
  2. >>> help(copy.copy)
Help on function copy in module copy:
copy(x)
Shallow copy operation on arbitrary Python objects.
See the module’s __doc__ string for more info.
The dir() function displays all the members of an object(any kind).
  1. >>> dir(copy.copy)
[‘__annotations__’, ‘__call__’, ‘__class__’, ‘__closure__’, ‘__code__’, ‘__defaults__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__get__’, ‘__getattribute__’, ‘__globals__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__kwdefaults__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__name__’, ‘__ne__’, ‘__new__’, ‘__qualname__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’]
9. Whenever you exit Python, is all memory de-allocated?
The answer here is no. The modules with circular references to other objects, or to objects referenced from global namespaces, aren’t always freed on exiting Python.
Plus, it is impossible to de-allocate portions of memory reserved by the C library.
10. What is monkey patching?
Dynamically modifying a class or module at run-time.
  1. >>> class A:
  2.   def func(self):
  3.       print("Hi")
  4. >>> def monkey(self):
  5. print "Hi, monkey"
  6. >>> m.A.func = monkey
  7. >>> a = m.A()
  8. >>> a.func()
Hi, monkey
11. What is a dictionary in Python?
A dictionary is something I have never seen in other languages like C++ or Java. It holds key-value pairs.
  1. >>> roots={25:5,16:4,9:3,4:2,1:1}
  2. >>> type(roots)
  3. <class 'dict'>
  4. >>> roots[9]
3
A dictionary is mutable, and we can also use a comprehension to create it.
  1. >>> roots={x**2:x for x in range(5,0,-1)}
  2. >>> roots
{25: 5, 16: 4, 9: 3, 4: 2, 1: 1}
12. What do you mean by *args and **kwargs?
In cases when we don’t know how many arguments will be passed to a function, like when we want to pass a list or a tuple of values, we use *args.
  1. >>> def func(*args):
  2.   for i in args:
  3.       print(i)
  4. >>> func(3,2,1,4,7)
3
2
1
4
7
**kwargs takes keyword arguments when we don’t know how many there will be.
  1. >>> def func(**kwargs):
  2.   for i in kwargs:
  3.       print(i,kwargs[i])
  4. >>> func(a=1,b=2,c=7)
a.1
b.2
c.7
The words args and kwargs are convention, and we can use anything in their place.

13. Write Python logic to count the number of capital letters in a file.
  1. >>> import os
  2. >>> os.chdir('C:\\Users\\lifei\\Desktop')
  3. >>> with open('Today.txt') as today:
  4.   count=0
  5.   for i in today.read():
  6.       if i.isupper():
  7.           count+=1
  8.   print(count)
26
14. What are negative indices?
Let’s take a list for this.
  1. >>> mylist=[0,1,2,3,4,5,6,7,8]
A negative index, unlike a positive one, begins searching from the right.
  1. >>> mylist[-3]
6
This also helps with slicing from the back:
  1. >>> mylist[-6:-1]
[3, 4, 5, 6, 7]
15. How would you randomize the contents of a list in-place?
For this, we’ll import the function shuffle() from the module random.
  1. >>> from random import shuffle
  2. >>> shuffle(mylist)
  3. >>> mylist
[3, 4, 8, 0, 5, 7, 6, 2, 1]
Q.17. Explain join() and split() in Python.
join() lets us join characters from a string together by a character we specify.
  1. >>> ','.join('12345')
‘1,2,3,4,5’
split() lets us split a string around the character we specify.
  1. >>> '1,2,3,4,5'.split(',')
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

No comments:

Post a Comment