Python Interview Questions and Answers to Make you Job-Ready

Since you have crossed the beginners’ level now its time to move one step ahead and level-up your skills and knowledge with the help of these advanced Python interview questions and answers for intermediates. As we all know that Python is the most preferred programming language in today’s world and has great career opportunities, this is the right time to step ahead of others and get ready for the technical round.

Here TechVidvan is providing you a series of 75+ Python Interview Questions and Answers in three parts:

Python interview questions and answers

Python Interview Questions and Answers for Intermediates

These Python interview questions and answers mainly focus on intermediates. Here we provide you top Python interview questions including some advanced and technical questions also with their answers which will definitely help you to crack your next interview. So, let’s get started.

Top Python Interview Questions and Answers

Q.1. How do you define data types in Python? How much memory does an integer hold?

You do not define data types in Python. It determines this at runtime based on the values of the underlying expressions.

Q.2. What are *args and **kwargs? Why do we call them so?

What if until runtime, you don’t know how many arguments your function will take? That could depend on the user, and hence, you must wait until runtime. You can define your function with *args or **kwargs as the list of parameters. *args can then take any number of arguments, and **kwargs will take any number of keyword arguments. Let’s take an example.

Code:

>>> def add(*args):
  return sum([arg for arg in args])

Code:

>>> add(1,2,3)

Output:

6

Code:

>>> add(1,2,3,4)

Output:

10

Code:

>>> add(1,2,3.0)

Output:

6.0

Code:

def sayhello(**kwargs):
  for key,value in kwargs.items():
    print(value)

>>> sayhello(fname="Ayushi",lname="Sharma")

Output:

Ayushi
Sharma

We call them *args and **kwargs for arguments and keyword arguments respectively, but we can call them anything else we want.

Q.3. How is shallow copying different from deep copying?

Shallow copying creates a new object – this holds the same objects as the original. So, any changes we make to this copy are visible in the original object as well. In deep copying, the new object holds copies of all the objects in the original, and so, any changes to these do not affect values in the original object.

To perform a shallow/deep copy:

Code:

>>> import copy
>>> a=[1,2,3]
>>> b=copy.copy(a)
>>> c=copy.deepcopy(a)

Q.4. What are match() and search()?

match() and search() are functions of the re module (for regular expressions) in Python. But they are slightly different. match() checks for a pattern match at the beginning of a string and search() checks for it in the entire string. Both return a Match object if found, else None.

Code:

>>> import re
>>> re.match('location','relocation')
>>> re.search('location','relocation')\

Output:

<re.Match object; span=(2, 10), match=’location’>

Q.5. What does the following code output?

Code:

'I like to watch movies'.isalnum()

In the interpreter, this prints False. It looks alphanumeric but isn’t. If it had a digit as well, it would return True.

Q.6. What is fabs()?

Let’s first talk about abs(). This is a built-in function that returns the absolute value of the argument.

Code:

>>> abs(2-3)

Output:

1

fabs() is a built-in function in the math module. It gives us the absolute value of a float argument.

Code:

>>> fabs(2.1-3.7)

Output:

1.6

Q.7. What is a suite in Python?

The suite is another name for a group of statements controlled by a clause. And the clause header starts with a uniquely identifying keyword and ends with a colon. In the following code, the part under if is the suite:

Code:

>>> if 2>1:
  print("Ok")
  print("Bye")

Output:

Ok
Bye

That applies for this one too:

Code:

>>> if 2>1: print("Ok"); print("Bye")

Output:

Ok
Bye

But this is invalid:

Code:

>>> if 2>1: if 2>-1: print("Ok")

Output:

SyntaxError: invalid syntax

Nesting is not possible for suites on the same lines as the clauses.

Q.8. How will you get the current time with Python?

I will use the time module for this:

Code:

>>> import time
>>> time.localtime(time.time())

Output:

time.struct_time(tm_year=2019, tm_mon=9, tm_mday=30, tm_hour=11, tm_min=43, tm_sec=51, tm_wday=0, tm_yday=273, tm_isdst=0)

Here, the time() function returns the current time in seconds since the Epoch, and localtime() converts it into a time tuple representing the local time. But a more efficient way to do this is:

Code:

>>> time.localtime()

Output:

time.struct_time(tm_year=2019, tm_mon=9, tm_mday=30, tm_hour=11, tm_min=45, tm_sec=41, tm_wday=0, tm_yday=273, tm_isdst=0)

Advanced Python Interview Questions and Answers

Now, let’s discuss some advanced Python Interview Questions and answers.

Q.9. Do you prefer Tkinter or PyQt?

Both Tkinter and PyQt are good GUI development libraries for Python. There are some reasons why you should go for PyQt over Tkinter:

  • It will give you some experience with Qt. If you then shift to some other technology, you will still be able to use it.
  • It is one of the best cross-platform interface toolkits.

However, sometimes, you may want to go for Tkinter:

  • PyQT is under the GPL license. So if you release your code, it should be under a compatible license. Go for Tkinter if you don’t want to spend money on this.
  • Also, Tkinter ships with Python. You will have to install PyQt if you want it.

Q.10. How will you destroy allocated memory in Python?

We do not need to explicitly deallocate memory in Python. Like in Java, the garbage collector takes care of allocating and deallocating memory. Memory leaks don’t happen often.

Python implements reference counting – it counts how often an object is referenced by other objects in the system. Each time a reference to an object is removed, its reference count is decremented. And when this becomes 0, the object is deallocated. Python runs its garbage collector when the difference between the number of allocations and the number of deallocations is greater than the threshold number.

Q.11. What is the self parameter?

Every method in a class takes the self parameter. This tells it to work on the current object of the class. When we talk about the properties of the current object of a class, we prefix the self parameter to it. We can call this anything else we want.

Code:

>>> class Fruit:
  def __init__(self,shape):
    self.shape='round'
  def show(self):
    print(self.shape)

Code:

>>> oj=Fruit('round')
>>> oj.show()

Output:

round

Q.12. Print the following star pattern:

   *
  * *
 * * *
* * * *
 * * *
  * *
   *

Code: To print the star pattern:

def star():
  for row in range(4):
    for space in range(3-row,0,-1):
      print(' ',end='')
    for star in range(row+1):
      print('* ',end='')
    print()
  for row in range(3):
    for space in range(row+1):
      print(' ',end='')
    for star in range(3-row):
      print('* ',end='')
    print()

star()

Q.13. Tell me one interesting thing about the Python interpreter.

In the interpreter, suppose we add the numbers 2 and 3.

Code:

>>> 2+3

Output:

5

Then, if we want to use this result and operate on that, we can use the _ (underscore) in its place.

Code:

>>> _*3

Output:

15

Q.14. Write a function to check whether a number is an Armstrong number.

Considering Armstrong numbers are those whose digits’ cubes sum up to the original number, let’s take an example.

153 = 13 + 53 + 33

Q.15. What is enumerate?

enumerate() is a built-in function. The enumerate object from the enumerate class gives us pairs with a count starting from 0, along with a value yielded by the iterable. Let’s take an example.

Code:

for index, value in enumerate(['Milk','eggs','cheese']):
  print(index, value)

Output:

0 Milk
1 eggs
2 cheese

Q.16. How is remove() different from del?

remove() is a built-in method on lists in Python. It lets us delete the first occurrence of an object in a list. To delete an object at a certain index, we can use the del keyword or the pop() method.

Code:

>>> list=[4,9,27,34,12,9,34]
>>> list.remove(34)
>>> list

Output:

[4, 9, 27, 12, 9, 34]

Code:

>>> del list[2]
>>> list

Output:

[4, 9, 12, 9, 34]

Code:

>>> list.pop(2)

Output:

12

Code:

>>> list

Output:

[4, 9, 9, 34]

Q.17. Can you overload constructors in Python?

If we overload the __init__ method of the Fruit class, creating an object of the first kind raises an error.

Code:

>>> class Fruit:
  def __init__(self,shape):
    self.shape=shape
  def __init__(self,shape,color):
    self.shape=shape
    self.color=color

Code:

>>> orange=Fruit('round','orange')
>>> apple=Fruit('round')

Output:

Traceback (most recent call last):
  File “<pyshell#200>”, line 1, in <module>
    apple=Fruit(’round’)
TypeError: __init__() missing 1 required positional argument: ‘color’

This is because there are not 2 __init__ methods- the second one exists, but the first one doesn’t.

Q.18. Can you count each item’s occurrences in a list without mentioning it?

We can turn the list into a set to avoid duplicates, then for each number in it, create a tuple from the number and its count. Put this in a list comprehension and return the list.

Code:

>>> def count_in_list(list):
  return [(num,list.count(num)) for num in set(list)]

Code:

>>> count_in_list([1,2,4,1,4,1,7,9,5])

Output:

[(1, 3), (2, 1), (4, 2), (5, 1), (7, 1), (9, 1)]

Q.19. List some common commands of the Python debugger.

The Python debugger (pdb) has many commands. Some are:

  • b – Add breakpoint
  • c – Continue execution
  • l – List entire source code
  • n – Move to next line
  • p – Print an expression
  • s – Execute next step

Technical Python Interview Questions and Answers

These are some frequently asked technical Python interview questions and answers. Let’s have a look:

Q.20. What are static variables?

A static variable is a class variable – it belongs to a class.

Code:

>>> class Fruit:
  name='fruit'
  def __init__(self, color):
    self.color=color

Code:

>>> orange=Fruit('orange')
>>> orange.name

Output:

‘fruit’

Code:

>>> Fruit.name

Output:

‘fruit’

Q.21. How will you assign values to class attributes?

We can do this in two ways – either while declaring the class or at runtime. This is how we do it at runtime:

Code:

>>> class Fruit:
  pass

Code:

>>> Fruit.name='fruit'
>>> Fruit.name

Output:

‘fruit’

This is called declaring attributes on the fly.

Q.22. Can you write a function to convert a string of text in title case?

This can easily be done using the title() built-in function.

Code:

>>> def to_title_case(text):
  return text.title()

Code:

>>> to_title_case('planet of the apes')

Output:

‘Planet Of The Apes’

Q.23. If you are given a string of text, how will you replace the spaces with periods? Also, add a period at the end.

There are two ways to do this:

1. Using join()

Code:

>>> print('.'.join('How are you?'.split(' '))+'.')

Output:

How.are.you?.

2. Using end

Code:

>>> for word in 'How are you?'.split(' '):
  print(word,end='.')

Output:

How.are.you?.

Q.24. What can follow a try-except block?

After a try-except block, there can be an else-clause or a finally-clause. If the code under the try-block does not raise an exception, the code under the else-clause runs. And the code under finally runs regardless of whether an exception occurred.

Q.25. What does the following code output?

>>> list=[1,2,3]
>>> list[4]
>>> list[4:]

The second line raises an IndexError because there is no index 4 on this list. But the slice does not raise an IndexError – it returns an empty list.

Q.26. How will you check the memory usage of an object?

The getsizeof() function gives us the sizes of an object in bytes.

Code:

>>> sys.getsizeof(7)

Output:

28

Code:

>>> sys.getsizeof(2)

Output:

28

Code:

>>> sys.getsizeof(2.5)

Output:

24

Code:

>>> sys.getsizeof(True)

Output:

28

Code:

>>> class Fruit:
  pass

Code:

>>> orange=Fruit()
>>> sys.getsizeof(orange)

Output:

56

Code:

>>> def sayhi():
  print("Hi")

Code:

>>> sys.getsizeof(sayhi)

Output:

136

Q.27. How will you specify path to a file in the parent of the current working directory?

If the current working directory is:

‘C:\\Users\\DataFlair\\Desktop\\one’

Suppose there are two folders on the Desktop- ‘one’ and ‘two. Each have a file text.txt. Then, the path to text.txt in two is:

‘..\two\\text.txt’

Open-Ended Python Interview Questions

Q.28. Why we should hire you?

Q.29. What do you expect from us?

Q.30. Do you have any previous work experience?

Q.31. What do you think about the future of Python programming language?

Q.32. What motivates you to do things better than others?

Q.33. Why are you interested in our company?

Q.34. Describe what is your ideal job?

Q.35. Tell me about the projects you have worked on? What approaches you have taken to complete that project?

Summary

This was all about TechVidvan’s Python interview questions and answers for intermediates. In this, we have covered top Python interview questions and some open-ended, advanced, and technical Python interview questions and answers with the help of examples which will easily help you to crack your next interview.

If you find this tutorial helpful, do share it on social media with others also.

All the best for your next interview!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.