Friday, 6 December 2019

Basic Python Interview Questions for Intermediates


Q.1. When is the else part of a try-except block executed?
In an if-else block, the else part is executed when the condition in the if-statement is False. But with a try-except block, the else part executes only if no exception is raised in the try part.
Q.2. If a list is nums=[0,1,2,3,4], what is nums[-1]?
This code does not throw an exception. nums[-1] is 4 because it begins traversing from right
Q.3. What is the PYTHONPATH variable?
PYTHONPATH is the variable that tells the interpreter where to locate the module files imported into a program. Hence, it must include the Python source library directory and the directories containing Python source code. You can manually set PYTHONPATH, but usually, the Python installer will preset it.
Q.4. 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’]
Q.5. Explain the output of the following piece of code-
  1. x=[‘ab’,’cd’]
  2. print(len(map(list,x)))
This actually gives us an error- a TypeError. This is because map() has no len() attribute in their dir().
Q.6. Explain a few methods to implement Functionally Oriented Programming in Python.
Sometimes, when we want to iterate over a list, a few methods come in handy.
a. filter()
Filter lets us filter in some values based on conditional logic.
  1. >>> list(filter(lambda x:x>5,range(8)))
[6, 7]
b. map()
Map applies a function to every element in an iterable.
  1. >>> list(map(lambda x:x**2,range(8)))
  1. [0, 1, 4, 9, 16, 25, 36, 49]
c. reduce()
Reduce repeatedly reduces a sequence pair-wise until we reach a single value.
  1. >>> from functools import reduce
  2. >>> reduce(lambda x,y:x-y,[1,2,3,4,5])
-13
Q.7. So what is the output of the following piece of code?
  1. x=[‘ab’,’cd’]
  2. print(len(list(map(list,x))))
This outputs 2 because the length of this list is 2. list(map(list,x)) is [[‘a’, ‘b’], [‘c’, ‘d’]], and the length of this is 2.
Q.8. Is del the same as remove()? What are they?
del and remove() are methods on lists/ ways to eliminate elements.
  1. >>> list=[3,4,5,6,7]
  2. >>> del list[3]
  3. >>> list
[3, 4, 5, 7]
  1. >>> list.remove(5)
  2. >>> list
[3, 4, 7]
While del lets us delete an element at a certain index, remove() lets us remove an element by its value.
Q.9. How do you open a file for writing?
Let’s create a text file on our Desktop and call it tabs.txt. To open it to be able to write to it, use the following line of code-
  1. >>> file=open('tabs.txt','w')
This opens the file in writing mode. You should close it once you’re done.
  1. >>> file.close()
Q.10. Explain the output of the following piece of code-
  1. >>> tuple=(123,'John')
  2. >>> tuple*=2
  3. >>> tuple
(123, ‘John’, 123, ‘John’)
In this code, we multiply the tuple by 2. This duplicates its contents, hence, giving us (123, ‘John’, 123, ‘John’). We can also do this to strings:
  1. >>> 'ba'+'na'*2
‘banana’
Q.11. Differentiate between the append() and extend() methods of a list.
The methods append() and extend() work on lists. While append() adds an element to the end of the list, extend adds another list to the end of a list.
Let’s take two lists.
  1. >>> list1,list2=[1,2,3],[5,6,7,8]
This is how append() works:
  1. >>> list1.append(4)
  2. >>> list1
[1, 2, 3, 4]
And this is how extend() works:
  1. >>> list1.extend(list2)
  2. >>> list1
[1, 2, 3, 4, 5, 6, 7, 8]
Q.12. What are the different file-processing modes with Python?
We have the following modes-
  • read-only – ‘r’
  • write-only – ‘w’
  • read-write – ‘rw’
  • append – ‘a’
We can open a text file with the option ‘t’. So to open a text file to read it, we can use the mode ‘rt’. Similarly, for binary files, we use ‘b’.
Q.13. What does the map() function do?
map() executes the function we pass to it as the first argument; it does so on all elements of the iterable in the second argument. Let’s take an example, shall we?
  1. >>> for i in map(lambda i:i**3, (2,3,7)):
  2. print(i)
8
27
343
This gives us the cubes of the values 2, 3, and 7.
Q.14. Explain try, raise, and finally.
These are the keywords we use with exception-handling. We put risky code under a try block, use the raise statement to explicitly raise an error, and use the finally block to put code that we want to execute anyway.
Q.15. What happens if we do not handle an error in the except block?
If we don’t do this, the program terminates. Then, it sends an execution trace to sys.stderr.
Q.16. Is there a way to remove the last object from a list?
Yes, there is. Try running the following piece of code-
  1. >>> list=[1,2,3,4,5
  2. >>> list.pop(-1)
5
  1. >>> list
[1, 2, 3, 4]
Q.17. How will you convert an integer to a Unicode character?
This is simple. All we need is the chr(x) built-in function. See how.
  1. >>> chr(52)
‘4’
  1. >>> chr(49)
‘1’
  1. >>> chr(67)
‘C’
Q.18. Explain the problem with the following piece of code-
  1. >>> def func(n=[]):
  2. #playing around
  3. pass
  4. >>> func([1,2,3])
  5. >>> func()
  6. >>> n
The request for n raises a NameError. This is since n is a variable local to func and we cannot access it elsewhere. It is also true that Python only evaluates default parameter values once; every invocation shares the default value. If one invocation modifies it, that is what another gets. This means you should only ever use primitives, strings, and tuples as default parameters, not mutable objects.
Q.19. What do you see below?
s = a + ‘[‘ + b + ‘:’ + c + ‘]’
This is string concatenation. If a, b, and c are strings themselves, then it works fine and concatenates the strings around the strings ‘[‘, ‘:’, and ‘]’ as mentioned. If even one of these isn’t a string, this raises a TypeError.
Q.20. So does recursion cause any trouble?
Sure does:
  • Needs more function calls.
  • Each function call stores a state variable to the program stack- consumes memory, can cause memory overflow.
  • Calling a function consumes time.
Q.21. What good is recursion?
With recursion, we observe the following:
  • Need to put in less efforts.
  • Smaller code than that by loops.
  • Easier-to-understand code.
Q.22. What does the following code give us?
  1. >>> b=(1)
Not a tuple. This gives us a plain integer.
  1. >>> type(b)
<class ‘int’>
To let it be a tuple, we can declare so explicitly with a comma after 1:
  1. >>> b=(1,)
  2. >>> type(b)
<class ‘tuple’>
Q.23. Why are identifier names with a leading underscore disparaged?
Since Python does not have a concept of private variables, it is a convention to use leading underscores to declare a variable private. This is why we mustn’t do that to variables we do not want to make private.
Q.24. Can you remove the whitespaces from the string “aaa bbb ccc ddd eee”?
I can think of three ways to do this.
Using join-
  1. >>> s='aaa bbb ccc ddd eee'
  2. >>> s1=''.join(s.split())
  3. >>> s1
‘aaabbbcccdddeee’
Using a list comprehension
  1. >>> s='aaa bbb ccc ddd eee'
  2. >>> s1=str(''.join(([i for i in s if i!=' '])))
  3. >>> s1
‘aaabbbcccdddeee’
Using replace()-
  1. >>> s='aaa bbb ccc ddd eee'
  2. >>> s1 = s.replace(' ','')
  3. >>> s1
‘aaabbbcccdddeee’
Q.25. How do you get the current working directory using Python?
Working on software with Python, you may need to read and write files from various directories. To find out which directory we’re presently working under, we can borrow the getcwd() method from the os module.
  1. >>> import os
  2. >>> os.getcwd()
‘C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37-32’


Q.26. 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.27. How do you remove the leading whitespace in a string?
Leading whitespace in a string is the whitespace in a string before the first non-whitespace character. To remove it from a string, we use the method lstrip().
  1. >>> ' Ayushi '.lstrip()
‘Ayushi ‘
As you can see, this string had both leading and trailing whitespaces. lstrip() stripped the string of the leading whitespace. If we want to strip the trailing whitespace instead, we use rstrip().
  1. >>> ' Ayushi '.rstrip()
‘ Ayushi’
Q.28. Below, we give you code to remove numbers smaller than 5 from the list nums. However, it does not work as expected. Can you point out the bug for us?
  1. >>> nums=[1,2,5,10,3,100,9,24]
  2. >>> for i in nums:
  3. if i<5:
  4. nums.remove(i)
  5. >>> nums
[2, 5, 10, 100, 9, 24]
This code checks for each element in nums- is it smaller than 5? If it is, it removes that element. In the first iteration, 1 indeed is smaller than 5. So it removes that from this list. But this disturbs the indices. Hence, it checks the element 5, but not the element 2. For this situation, we have three workarounds:
Create an empty array and append to that-
  1. >>> nums=[1,2,5,10,3,100,9,24]
  2. >>> newnums=[]
  3. >>> for i in nums:
  4. if i>=5:
  5. newnums.append(i)
  6. >>> newnums
[5, 10, 100, 9, 24]
Using a list comprehension-
  1. >>> nums=[1,2,5,10,3,100,9,24]
  2. >>> newnums=[i for i in nums if i>=5]
  3. >>> newnums
[5, 10, 100, 9, 24]
Using the filter() function-
  1. >>> nums=[1,2,5,10,3,100,9,24]
  2. >>> newnums=list(filter(lambda x:x>=5, nums))
  3. >>> newnums
[5, 10, 100, 9, 24]
Q.29. What is the enumerate() function in Python?
enumerate() iterates through a sequence and extracts the index position and its corresponding value too.
Let’s take an example.
  1. >>> for i,v in enumerate(['Python','C++','Scala']):
  2. print(i,v)
0 Python
1 C++
2 Scala
Q.30. How will you create the following pattern using Python?
*
**
***
****
*****
We will use two for-loops for this.
  1. >>> for i in range(1,6):
  2. for j in range(1,i+1):
  3. print('*',end='')
  4. print()
Q.31. Where will you use while rather than for?
Although we can do with for all that we can do with while, there are some places where a while loop will make things easier-
python advanced interview questions
  • For simple repetitive looping
  • When we don’t need to iterate through a list of items- like database records and characters in a string.
Q.32. Take a look at this piece of code:
  1. >>> A0= dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
  2. >>> A1= range(10)
  3. >>> A2= sorted([i for i in A1 if i in A0])
  4. >>> A3= sorted([A0[s] for s in A0])
  5. >>> A4= [i for i in A1 if i in A3]
  6. >>> A5= {i:i*i for i in A1}
  7. >>> A6= [[i,i*i] for i in A1]
  8. >>> A0,A1,A2,A3,A4,A5,A6
What are the values of variables A0 to A6? Explain.
Here you go:
A0= {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4, ‘e’: 5}
A1= range(0, 10)
A2= []
A3= [1, 2, 3, 4, 5]
A4= [1, 2, 3, 4, 5]
A5= {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6= [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
Now to find out what happened. A0 zips ‘a’ with 1, ‘b’ with 2, and so on. This results in tuples, which the call to dict() then turns into a dictionary by using these as keys and values.
  • A1 gives us a range object with start=0 and stop=10.
  • A2 checks each item in A1- does it exist in A0 as well? If it does, it adds it to a list. Finally, it sorts this list. Since no items exist in both A0 and A1, this gives us an empty list.
  • A3 takes each key in A0 and returns its value. This gives us the list [1,2,3,4,5].
  • A4 checks each item in A1- does it exist in A3 too? If it does, it adds it to a list and returns this list.
  • A5 takes each item in A1, squares it, and returns a dictionary with the items in A1 as keys and their squares as the corresponding values.
  • A6 takes each item in A1, then returns sublists containing those items and their squares- one at a time.
Q.33. Does Python have a switch-case statement?
In languages like C++, we have something like this:
  1. switch(name)
  2. {
  3. case ‘Ayushi’:
  4. cout<<”Monday”;
  5. break;
  6. case ‘Megha’:
  7. cout<<”Tuesday”;
  8. break;
  9. default:
  10. cout<<”Hi, user”;
  11. }
But in Python, we do not have a switch-case statement. Here, you may write a switch function to use. Else, you may use a set of if-elif-else statements. To implement a function for this, we may use a dictionary.
  1. >>> def switch(choice):
  2. switcher={
  3. 'Ayushi':'Monday',
  4. 'Megha':'Tuesday',
  5. print(switcher.get(choice,'Hi, user'))
return
  1. >>> switch('Megha')
Tuesday
  1. >>> switch('Ayushi')
Monday
  1. >>> switch('Ruchi')
Hi, user
Here, the get() method returns the value of the key. When no key matches, the default value (the second argument) is returned.
Q.34. Differentiate between deep and shallow copy.
python basic interview questions
A deep copy copies an object into another. This means that if you make a change to a copy of an object, it won’t affect the original object. In Python, we use the function deepcopy() for this, and we import the module copy. We use it like:
  1. >>> import copy
  2. >>> b=copy.deepcopy(a)
A shallow copy, however, copies one object’s reference to another. So, if we make a change in the copy, it will affect the original object. For this, we have the function copy(). We use it like:
  1. >>> b=copy.copy(a)


Q.35. Can you make a local variable’s name begin with an underscore? (developer)
You can, but you should not. This is because:
Local variables indicate private variables of a class, and so, they confuse the interpreter.
Q.36. Is a NumPy array better than a list?
NumPy arrays have 3 benefits over lists:
  • They are faster
  • They require less memory
  • They are more convenient to work with
Q.37. If you installed a module with pip but it doesn’t import in your IDLE, what could it possibly be?
  • Well, for one, it could be that I installed two versions of Python on my system- possibly, both 32-bit and 64-bit.
  • The Path variable in my system’s environment variables is probably set to both, but one of them prior to the other- say, the 32-bit.
  • This made the command prompt use the 32-bit version of pip to install the module I chose.
  • When I ran the IDLE, I ran the 64-bit version.
As this sequence of events unlapped, I couldn’t import the module I just installed.
Q.38. Based on your previous answer, how will you solve this issue?
I could do two things.
  • The temporary solution- I will add the path to sys manually every time I work on a new session of the interpreter.
  1. >>> sys.path.append('C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37\\Scripts')
  • The permanent solution- I will update the value of Path in my environment variables to hold the location of the Scripts folder for the 64-bit version first.
Q.39. If while installing a package with pip, you get the error No matching installation found, what can you do?
In such a situation, one thing I can do is to download the binaries for that package from the following location:
https://www.lfd.uci.edu/~gohlke/pythonlibs/
Then, I can install the wheel using pip.

Q.40. How can you keep track of different versions of code?
To make this happen, we implement version control. For this, one tool you can use is Git.
Q.41. How do you debug a program in Python? Answer in brief.
To debug a Python program, we use the pdb module. This is the Python debugger. If we start a program using pdb, it will let us step through the code.
Q.42. Can I dynamically load a module in Python?
Dynamic loading is where we do not load a module till we need it. This is slow, but lets us utilize the memory more efficiently. In Python, you can use the importlib module for this:
  1. import importlib
  2. module = importlib.import_module('my_package.my_module')
Q.43. Which methods/functions do we use to determine the type of instance and inheritance?
Here, we talk about three methods/functions- type(), isinstance(), and issubclass().
a. type()
This tells us the type of object we’re working with.
  1. >>> type(3)
<class ‘int’>
  1. >>> type(False)
<class ‘bool’>
  1. >>> type(lambda :print("Hi"))
<class ‘function’>
  1. >>> type(type)
<class ‘type’>
b. isinstance()
This takes in two arguments- a value and a type. If the value is of the kind of the specified type, it returns True. Else, it returns False.
  1. >>> isinstance(3,int)
True
  1. >>> isinstance((1),tuple)
False
  1. >>> isinstance((1,),tuple)
True
c. issubclass()
This takes two classes as arguments. If the first one inherits from the second, it returns True. Else, it returns False.
  1. >>> class A: pass
  2. >>> class B(A): pass
  3. >>> issubclass(B,A)
True
  1. >>> issubclass(A,B)
False
Q.44. Are methods and constructors the same thing?
No, there are subtle but considerable differences-
  • We must name a constructor in the name of the class; a method name can be anything.
  • Whenever we create an object, it executes a constructor; whenever we call a method, it executes a method.
  • For one object, a constructor executes only once; a method can execute any number of times for one object.
  • We use constructors to define and initialize non-static variables; we use methods to represent business logic to perform operations.
Q.45. What is a Python module?
A module is a script in Python that defines import statements, functions, classes, and variables. It also holds runnable Python code. ZIP files and DLL files can be modules too. The module holds its name as a string that is in a global variable.
Q.46. What are the file-related modules we have in Python?
We have the following libraries and modules that let us manipulate text and binary files on our file systems-
os
os.path
shutil
Q.47. Explain, in brief, the uses of the modules sqlite3, ctypes, pickle, traceback, and itertools.
  • sqlite3- Helps with handling databases of type SQLite
  • ctypes- Lets create and manipulate C data types in Python
  • pickle- Lets put any data structure to external files
  • traceback- Allows extraction, formatting, and printing of stack traces
  • itertools– Supports working with permutations, combinations, and other useful iterables.
Q.48. Explain inheritance in Python.
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).
Python Interview Questions - inheritance
Inheritance lets us reuse our code, and also makes it easier to create and maintain applications. Python supports the following kinds of inheritance:
  • Single Inheritance- A class inherits from a single base class.
  • Multiple Inheritance- A class inherits from multiple base classes.
  • Multilevel Inheritance- A class inherits from a base class, which, in turn, inherits from another base class.
  • Hierarchical Inheritance- Multiple classes inherit from a single base class.
  • Hybrid Inheritance- Hybrid inheritance is a combination of two or more types of inheritance.
Q.49. Explain memory management in Python.
Objects and data structures in Python lie on a private heap. The Python memory manager internally manages this. It delegates some work to object-specific allocators while ensuring they operate only within the private heap. Actually, the interpreter manages this heap; the user has no control over it- not even if they manipulate object pointers to memory blocks inside the heap. The Python memory manager allocates heap space to objects and other internal buffers on demand.
Q.50. 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
Q.51. How would you make a Python script executable on Unix?
For this to happen, two conditions must be met:
  • The script file’s mode must be executable
  • The first line must begin with a hash(#). An example of this will be: #!/usr/local/bin/python
Q.52. What functions or methods will you use to delete a file in Python?
For this, we may use remove() or unlink().
  1. >>> import os
  2. >>> os.chdir('C:\\Users\\lifei\\Desktop')
  3. >>> os.remove('try.py')
  4. >>>
When we go and check our Desktop, the file is gone. Let’s go make it again so we can delete it again using unlink().
  1. >>> os.unlink('try.py')
  2. >>>
Both functions are the same, but unlink is the traditional Unix name for it.
Q.53. Can you write a function to generate the following pyramid?
 *
 ***
 *****
 *******
*********
  1. def pyramid(n):
  2. for row in range(n):
  3. for space in range(n-row):
  4. print(' ',end='')
  5. for star in range(row):
  6. print('*',end='')
  7. for star in range(row+1):
  8. print('*',end='')
  9. print()
  10. pyramid(5)
Q.54. How will you print the contents of a file?
  1. >>> try:
  2. with open('tabs.txt','r') as f:
  3. print(f.read())
  4. except IOError:
  5. print("File not found")
Q.55. Explain lambda expressions. When would you use one?
When we want a function with a single expression, we can define it anonymously. A lambda expression may take input and returns a value. To define the above function as a lambda expression, we type the following code in the interpreter:
  1. >>> (lambda a,b:a if a>b else b)(3,3.5)
3.5
Here, a and b are the inputs. a if a>b else b is the expression to return. The arguments are 3 and 3.5.
It is possible to not have any inputs here.
  1. >>> (lambda :print("Hi"))()
Hi
Q.56. What is a generator?
Python generator produces a sequence of values to iterate on. This way, it is kind of an iterable.
We define a function that ‘yields’ values one by one, and then use a for loop to iterate on it.
  1. >>> def squares(n):
  2. i=1
  3. while(i<=n):
  4. yield i**2
  5. i+=1
  6. >>> for i in squares(7):
  7. print(i)
1
4
9
16
25
36
49
Q.57. So, what is an iterator, then?
An iterator returns one object at a time to iterate on. To create an iterator, we use the iter() function.
odds=iter([1,3,5,7,9])
Then, we call the next() function on it every time we want an object.
  1. >>> next(odds)
1
  1. >>> next(odds)
3
  1. >>> next(odds)
5
  1. >>> next(odds)
7
  1. >>> next(odds)
9
And now, when we call it again, it raises a StopIteration exception. This is because it has reached the end of the values to iterate on.
  1. >>> next(odds)
Traceback (most recent call last):
File “<pyshell#295>”, line 1, in <module>
next(odds)
StopIteration
Q.58. Okay, we asked you about generators and iterators, and you gave us the right answers. But don’t they sound similar?
python scripting interview questions
They do, but there are subtle differences:
  • For a generator, we create a function. For an iterator, we use in-built functions iter() and next().
  • For a generator, we use the keyword ‘yield’ to yield/return an object at a time.
  • A generator may have as many ‘yield’ statements as you want.
  • A generator will save the states of the local variables every time ‘yield’ will pause the loop. An iterator does not use local variables; it only needs an iterable to iterate on.
  • Using a class, you can implement your own iterator, but not a generator.
  • Generators are fast, compact, and simpler.
  • Iterators are more memory-efficient.
Q.59. What is a decorator?
A decorator is a function that adds functionality to another function without modifying it. It wraps another function to add functionality to it. Take an example.
  1. >>> def decor(func):
  2. def wrap():
  3. print("$$$$$$$$$$$$$$$$$")
  4. func()
  5. print("$$$$$$$$$$$$$$$$$")
return wrap
  1. >>> @decor
  2. def sayhi():
  3. print("Hi")
  4. >>> sayhi()
$$$$$$$$$$$$$$$$$
Hi
$$$$$$$$$$$$$$$$$
Decorators are an example of metaprogramming, where one part of the code tries to change another.
Q.60. What is Monkey Patching?
Monkey patching refers to modifying a class or module at runtime (dynamic modification). It extends Python code at runtime.
For example:
  1. from pkg.module import MyClass
  2. def sayhello(self):
  3. print("Hello")
  4. MyClass.sayhello=sayhello

                       Hope you have enjoyed the above Python Interview Questions.
                           Let me know in comment section if have any questions..........