Python Interview Questions – Success Mantra for Your First Python Interview

Python Interview Questions for Freshers

Python is the most used programming language in this world. If you want to make your career as a Python expert and become successful, then here is the first step towards your career success. TechVidvan is providing you a series of 75+ Python Interview Questions and Answers in three parts:

To begin with, in this Python interview questions article, we have selected some basic Python interview questions and answers for beginners, which include a balance of both theoretical and practical concepts. These Python interview questions will help you in boosting your preparation for your first interview. So, let’s get started.

Python Interview Questions and Answerstop python interview questions

In this Python interview questions article, we have provided some basic, frequently asked, open-ended and top Python interview questions for beginners or freshers with their answers. Let’s discuss them one by one.

Basic Python Interview Questions and Answers

Q.1. Is indentation mandatory in Python? Why?

Yes, indentation is mandatory in Python. Since it does not use curly braces, you need to indent code blocks equally so it can understand what is part of a block and what isn’t. This is an error:

Code:

if 2>1{

Output:

SyntaxError: invalid syntax

Q.2. What is PEP 8?

PEP is the Python Enhancement Proposal 8 – it is a style guide for Python. It has coding conventions and guidelines to help improve the readability of code and make it consistent. It has recommendations about indentation, line length, blank lines, source file encoding, imports, string quotes, whitespace, trailing commas, comments and docstrings, naming conventions, and some programming recommendations.

Q.3. What does the zip() function do?

This function zips objects together – it maps similar indices of multiple containers, then returns a zip object. This is its syntax:

Syntax:

zip(iterator1, iterator2, iterator3)

For example, list(zip([1,2,3],[4,5],[‘a’,’b’,’c’])) gives us [(1, 4, ‘a’), (2, 5, ‘b’)].

Learn everything about Python zip function.

Q.4. Explain the swapcase() function?

swapcase() is a method in the str class; it converts uppercase characters to lowercase, and vice-versa.

Code:

>>> 'maxyear'.swapcase()

Output:

MAXYEAR

Code:

>>> ‘Title’.swapcase()

Output:

tITLE

Q.5. If you have 10 cards in your hands ([2,4,7,8,9,J,Q,K,A,A]), can you shuffle them with Python?

We will use the shuffle() method from the random module here. This method shuffles a list in place.

Code:

>>> from random import shuffle
>>> cards=['2','4','7','8','9','J','Q','K','A','A']
>>> shuffle(cards)
>>> ''.join(cards)

Output:

‘8QA4J2KA79’

Q.6. If you want to work with files in Python, which module will you use?

Python has the following options for text and binary file handling –

  • os (and os.path)
  • shutil

Using these, you can create a file, copy its content, and also delete it.

Q.7. What various file processing modes does Python support?

With Python, you can open files in four modes- read-only, write-only, read-write, and append modes.

  • Read-only mode (‘r’) – Open a file for reading, default mode
  • Write-only mode (‘w’) – Open a file for writing, replace any data or create new file
  • Read-write mode (‘rw’) – Open a file for updating
  • Append mode (‘a’) – Append to the end of the file

Q.8. How is Python 2.x different from Python 3.x?

Python 2 and 3 are similar but slightly different:

  • The print statement in Python 2 was replaced by the print() function in Python 3.
  • In Python 3, strings are in Unicode by default. Python 2 strings are in ASCII.
  • Some libraries for Python 3 are not compatible with Python 2.
  • Python 2 also had a raw_input() function for input. It also had the xrange() function.
  • Python 2 is expiring on Jan 1, 2020 – by then, legacy code in Python 2 can be switched to Python 3.
  • Division in Python 2 gives us an integer, but in Python 3, it gives us a float.

Q.9. What is enumerate() used for?

This function iterates through a sequence and gets the index position and value for each item.

Code:

for index, value in enumerate(['milk','butter','cheese']):
  print(index, value)

Output:

0 milk
1 butter
2 cheese

Q.10. What is PYTHONPATH?

This is an environment variable similar to PATH. Whenever you import a module, the interpreter looks for it at the location specified by this variable. It augments the default search path for module files. This variable’s value is a string with a list of directories for the sys.path directory list. One good use of this is to import our own code which isn’t an installable package yet.

Q.11. And what are PYTHONSTARTUP, PYTHONCASEOK, AND PYTHONHOME?

PYTHONSTARTUP holds the path to an initialization file with some Python code. This runs every time you start the interpreter before the first prompt is displayed.

If PYTHONCASEOK is set, Python ignores the case in import statements. This is only for Windows and OS X. To activate it, you can set it to any value.

And PYTHONHOME changes the location of the standard Python libraries.

To do this on Windows, get to System Properties, and then click on Environment Variables. Then, add a new Environment Variable and its value.

Q.12. How are lists different than tuples?

Lists and tuples are two data types in Python – these are collections of objects. But they are quite different, and here’s how:

Lists are mutable, tuples are immutable. You can modify a list, but not a tuple.

Code:

>>> a=[1,2,3]
>>> a[2]=4
>>> a

Output:

[1, 2, 4]

Code:

>>> b=(1,2,3)
>>> b[2]=4

Output:

Traceback (most recent call last):
  File “<pyshell#7>”, line 1, in <module>
    b[2]=4
TypeError: ‘tuple’ object does not support item assignment
  • Lists are slower than tuples.
  • Tuples can be dictionary keys because they’re immutable; lists cannot because they are mutable.
  • We cannot sort a tuple, but we can sort a list with sort().

Know in detail how Python lists are different than Python tuples with TechVidvan.

Q.13. How can you remove the last object from a list?

Consider a list with three objects – [1,2,3]. We can delete the last object this way:

Code:

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

Output:

[1, 2, 3]

Code:

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

Output:

[1, 2]

Get detailed insights of Python lists by TechVidvan.

Q.14. Explain the map() function in Python.

This function makes an iterator which operates on arguments from each iterable, and computes the function. Like zip(), this exhausts with the shortest iterable.

Code:

for i in map(lambda num:num**2, [1,2,3]):
  print(i)

Output:

1
4
9

Frequently Asked Python Interview Questions and Answers

Now, let’s discuss the most frequently asked Python interview questions with their answers.

Q.15. What is __init__ in Python?

__init__ is a magic method and is like a constructor in C++. It is used to initialize objects. Whenever a new object is created, this method is called and it allocates memory for the new object. If you do not provide an __init__ for a class, Python will use its default version.

Code:

>>> class marks:
  def __init__(self):
    self.marks=33
  def show(self):
    print("You scored",self.marks)

Code:

>>> Amy=marks()
>>> Amy.show()

Output:

You scored 33

Q.16. Is Python fully object-oriented?

Everything in Python is an object. However, it’s not fully object-oriented because it does not support strong encapsulation, which is the bundling of data with methods and restricting access to some components. Also, Guido doesn’t like hiding things.

Q.17. What is loop interruption?

Interrupting a loop means terminating it prematurely before it can run full iterations. Python has three loop interruption statements:

  • break – This breaks out of the loop and starts executing the next statement after it.
  • continue – This skips to the next iteration without executing the statements after it.
  • pass – You can use this when you don’t know what to put in a loop.

Have a quick revision of loops in Python.

Q.18. Write a program to check whether a string is a palindrome.

Code:

>>> def palindrome(string):
  return string==string[::-1]

Code:

>>> palindrome('nun')

Output:

True

Code:

>>> palindrome('pandas are good')

Output:

False

Code:

>>> palindrome('nuns')

Output:

False

Q.19. Is Python pass-by-value or pass-by-reference?

Python is neither pass-by-value nor pass-by-reference. It is pass-by-object-reference. This means changes to a mutable object passed to a function will change the original, and those to an immutable object passed to a function will not affect the original.

Q.20. What is a namespace?

A name is an identifier (a name we give to objects). A namespace is a collection of names. This is a mapping of every name to the object it identifies. We can have multiple namespaces, and hence, avoid name collisions. Even when we call a function, it creates a local namespace with all the names defined in it.

Q.21. What is %s in Python?

Python lets us embed values into strings. There are 3 methods for this – f-strings, the format() method, and the % operator. You can use it this way –

Code:

>>> cats=7
>>> print("I have %d cats" %(cats))

Output:

I have 7 cats

Q.22. Is it mandatory for a function to return a value?

A function does not have to return a value, but it can. You can also make a function return None.

Q.23. What is the id() function in Python?

The id() function returns the identity of an object – this is unique for objects existing at a time.

Code:

>>> id(2)

Output:

140718707470624

Code:

>>> a=2
>>> id(a)

Output:

140718707470624

Code:

>>> b=2.0
>>> id(b)

Output:

2235136553104

Top Python Interview Questions and Answers

Here are the top Python interview questions for beginners with their answers.

Q.24. Does Python have a main() method?

Many programming languages have an entry point (the main() method or function). Python is interpreted and executes one line at a time. However, it does have a main() method – this is useful when we want to run it as a script. We can also override it. If this is in maindemo.py:

Code:

def sayhello():
    print("Hello")

if __name__=='__main__':
    sayhello()

And we run this in the command prompt:

Code:

C:\Users\ADMIN\Desktop>py maindemo.py

It gives us:

Output:

Hello

Q.25. In the above question, what is __name__?

There’s no way to access the built-in __main__ method. So when we run a script, Python starts executing code at 0 indentations. We compare the value of __name__ with the value __main__ to see if main() was called.

Q.26. How will you use multiple print statements to print in the same line?

We can use the end parameter of the print() function for this:

Code:

for num in range(7):
  print('*',end='')

Output:

*******

Code:

for num in range(7):
  print('*',end='\\')

Output:

*\*\*\*\*\*\*\

Q.27. What is GIL?

GIL is the Global Interpreter Lock. Python does not implement locks for each thread but has one lock for the interpreter – the GIL. When a thread holds the GIL, no other thread can execute in that interpreter. This means Python is not truly multithreaded.

Q.28. What is closure?

When a function is nested inside another, the inner function remembers the value of the argument passed to the outer function. This value gets bound to it. This is called closure.

Code:

>>> def outer(num):
  def inner(multiplier):
    return num*multiplier
  return inner

Code:

>>> f=outer(7)
>>> print(f(3))

Output:

21

Q.29. What is globals()?

The globals() function returns the current global symbol table as a dictionary. This has names of all the variables, methods, and classes in use.

Code:

>>> globals()

Output:

{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class ‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘num’: 6, ‘outer’: <function outer at 0x00000156106474C8>, ‘f’: <function outer.<locals>.inner at 0x0000015610647798>}

We can alter a value in this since it’s a dictionary:

Code:

>>> a=7
>>> globals()['a']=4
>>> a

Output:

4

Q.30. What happens if we try to multithread on uniprocessor system?

Since only one thread can execute at a time in the interpreter, multithreading will degrade performance on a single-processor system.

Open-Ended Python Interview Questions

Q.31. Why do you want to work in our company?

Q.32. What are your long-term goals?

Q.33. What makes you choose Python over other languages?

Q.34. Have you worked on any real-time Python projects? What challenges did you face?

Summary

These were the Python interview questions for beginners. If you will practice all the above interview questions before your interview, it will definitely help you in cracking your interview.

If you have any doubts in TechVidvan’s Python interview questions article, do let us know in the comment section.

All the best for your next interview!!