Python Interview Questions

Do you have an upcoming interview and are worried about what the questions might be? Do not worry! Here are some frequently asked interview questions along with their solutions.

What is Python?

Python is a high-level, general-purpose interpreted programming language widely used in different spheres of technical coding.

What is meant by an interpreted programming language?

Any programming language that is not converted in the machine level code before runtime is called an interpreted programming language. Python is an interpreted language. In other words, Python programs do not have to be compiled before they are run.

What are the various advantages of Python?

Python is a widely-used programming language and is beneficial in several ways. A few of its advantages are:

  1. It is easy to learn and use
  2. It is interpreted
  3. It is object-oriented
  4. It is free and open-source
  5. It has several in-built data structures
  6. It is very flexible with many modules available
  7. It can work on any platform without affecting its performance.

What is the difference between lists and tuples in Python?

Python Interview Questions 2

In Python, lists are mutable, whereas tuples are immutable. It means that lists can be edited, but tuples cannot be edited. Also, lists are slower than tuples. The two are the most commonly used data structures in Python; however, both are different.

Numberlist = [1,2,3,4,5]
Numbertuple = (1,2,3,4,5)
print(Numberlist)
print(Numbertuple)

Output:

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

Python is not a case-sensitive language. True or False

False. Python is a case sensitive language.

Explain a few features of Python.

Python is a widely-used programming language, and its popularity is growing by the day. A few features of Python are:

  1. Interpreted: Python is an interpreted language. In other words, Python programs do not have to be compiled before they are run. However, this is not the case in conventional programming languages like C and C++. A few other interpreted languages include PHP and Ruby.
  2. No access specifiers: In Python, there are no access specifiers like public, private and protected like in C++ or Java. However, Python supports object-oriented programming because it allows the definition of classes and supports inheritance and composition.
  3. Codes are written quickly: Python is an easy to use programming language, and you can write the code with ease. However, the running of programs is slower than the compiled programs of other languages.
  4. Wide Applications: Python can be used in any technological sphere, be it web applications, scientific modelling, or any other.

How is memory managed in Python?

Python Interview Questions 3

In Python, the Python private heap space is used for memory management. All the objects and data structures in Python are located in a private heap. This private heap is not accessible to the programmer. Instead, it is taken care of by the python interpreter. Python’s memory manager does the allocation of heap space for Python objects. Python also has an inbuilt garbage collector, which recycles all the unused memory and makes it available to the heap space. Hence, there is no role of the programmer in the memory management process.

What is namespace in Python?

In Python, the namespace is a naming system used to make sure that names are unique. The use of namespace helps to avoid naming conflicts of functions or variables.

What are python modules?

Files that contain previously coded python executable documentation are known as Python modules. These modules can be functions, classes or variables. A Python module is saved with .py extension and is executable in all systems that have Python installed.

Name some built-in modules in Python?

Some of the commonly used built-in modules are:

  • os
  • sys
  • math
  • random
  • data time

What are local variables and global variables in Python?

In Python, variables can be declared in two ways, either globally or locally. Global variables are declared outside a function or in the global space. These variables are accessible by any function, in the program. Local Variables are the variables that are declared inside a function. Local variables can only be accessed by the function in which they have been defined.

Example:

a=10
def add():
    b=20
    c=a+b
    print(c)
add()

Output:

30

In this case, a is a global variable and b and c are local variables. In case you try to use the statement print(c) outside the add function, the code might throw an error. Hence, local variables cannot be accessed outside the function body.

Why is indentation so crucial in Python?

Python does not use parenthesis or brackets to define codes; instead, it only works based on the correct indentation. Therefore, it is essential to maintain proper indentation while writing a python code. Otherwise, the output may vary. Indentation matters most in loops because the code’s output may entirely change than the desired outcome.

For example:

x = 0
while x < 3:
    print("hello world", x)
    x += 1

Output:

hello world 0
hello world 1
hello world 2

Okay No have a look at this code!!

x = 0
while x < 3:
    print("hello world", x)
x += 1

This code is not intended correctly, and therefore it runs as an infinite loop. Therefore, the slightest of errors in indenting a python code can lead to unnecessary errors or infinite loops.

What is type conversion in Python?

In Python, the conversion of one data-type to another is referred to as type conversion. A few functions used for type conversion in Python are:

  • int (): converts any data type into integer type
  • float(): converts any data type into float type or decimal values
  • ord(): converts characters into integer
  • tuple(): This function is used to convert a data set to a tuple.
  • list(): This function is used to convert any data type to a list type.
  • str(): Used to convert an integer into a string.

What is the difference between Arrays and lists in Python?

Python Interview Questions 4

In Python, whether you use an array or a list, they store data in the same way. However, arrays can hold data of a single type only whereas lists can hold data of any data type. Also, arrays cannot be resized and are less flexible than lists.

Example:

import array as arr
arr = [10, 20, 50, 40, 30]
print(arr)
my_list = ["John", 1735, 'P', True]
print(my_list)

Output:

[10,20,50,40,30]
['John', 1735, 'P', True]

What are the functions in Python?

A function is a block of code that defines a set of actions to be performed when called. In Python, the keyword def is used to define a function. Functions are used to reuse code without having to re-write lines of codes again and again.

Example:

def add():
    a = 10
    b = 20
    c = a+b
    print(c)
add()

Output:

30

Here add is a function, used to add two numbers.

What is a lambda function?

In Python, there is a concept of defining anonymous functions. Any such anonymous function is known as a lambda function. A Lambda function can have many parameters, but, it cannot have more than one statement.

Example:

x = lambda a,b : a+b
print(x(10, 20))

Output:

30

Explain the loops in Python with examples.

Python Interview Questions 5

Like any other programming language, Python also allows the programmer to execute a piece of code multiple times using a loop. A loop statement’s basic functionality is to allow us to execute a statement or group of statements multiple times. There are different kinds of loops in Python. While all the loops effectively perform the same function, they differ in their syntax and condition checking time.

Python Interview Questions 6

  1. While Loop

In Python, a while loop is used to repeatedly execute a set of statements until a given condition is satisfied. And when the condition is not satisfied, the line immediately after the loop in the program is executed.

Syntax:

while expression:
    statement(s)

While programming in Python, one has to use the correct indentation as Python does not use parentheses to identify different code blocks. Thus, all the statements inside the while loop must be intended by the same space (unless there is another nested loop inside).

Example Code:

count = 0
print("Beginning the while loop")
while (count < 10):    
    count = count + 1
    print(count)
print("The loop has ended")

OUTPUT:

Python Interview Questions 7

  1. For-in Loop

For loops are used for sequential traversal like traversing a list or string or array etc. In Python, the syntax varies from that of the C language. The for-in loop is used to iterate over a range that is specified by the programmer.

Syntax:

for iterator_variable in sequence:
    statements(s)

Example Code:

x = 5
print("Beginning of for in loop")
for i in range(0, x):
    print(i)

OUTPUT:

Python Interview Questions 8

 

  1. Nested Loops

Python allows the programmer to use a loop inside a loop. Such loops are known as nested loops. We can use one or more loops inside any other while or for a loop. There are various possibilities for using nested loops, while inside a for loop, inside another for, or while inside while, and so on.

Example Code:

i=6
while(i>0):
    j=6
    while(j>i):
        print("*",end=' ')
        j-=1
    i-=1
    print()

OUTPUT:

Python Interview Questions 9

What are loop control statements? What are the various loop control statements in Python?

When working with loops, sometimes we need statements to control the actions of the loops. These are known as loop control statements. Loop control statements change the execution of a loop from its typical sequence. Python has three primitive loop control statements.

  1. Break statement
  2. Continue statement
  3. Pass statement
  4. Break Statement

The break statement terminates the loop and transfers execution to the statement following the loop. This statement is used to move out of a loop. It is mostly used with an if condition inside a loop.

For example: In a given set of fruits, we exit from the loop if the fruit is banana.

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

OUTPUT:

Python Interview Questions 10

In this case, the list of fruits is iterated, until we reach the banana, and then the loop exits without printing the rest of the fruits.

  1. Continue statement

The continue statement causes the loop to skip the remainder of its body and immediately return to the condition before this step. In simpler terms, with the continue statement, we can stop the current iteration of the loop and continue with the next.

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)

OUTPUT:

Python Interview Questions 11

In this case, the list of fruits is iterated. When the iterating variable comes across ‘banana’, it skips it, continues in the loop, and prints the next item.

  1. Pass Statement

Python’s pass statement is used when a statement is present in a code, but there is no block of statements inside the loop. Loops cannot be empty, but if for some reason we have a loop with no content, we put in the pass statement to avoid getting an error.

for x in [0, 1, 2]:
    pass

What does the statement [::-1} do in Python?

[::-1] is used to reverse the order of a sequenced data structure

For example:

import array as arr
My_Array = arr.array('i',[1,2,3,4,5])
print(My_Array [::-1])
print(My_Array)

Output:

array('i', [5, 4, 3, 2, 1])
array('i', [1, 2, 3, 4, 5])

[::-1] reprints the reversed copy of ordered data structures such as an array or a list. However, the original array or list remains unchanged.

Using an example demonstrate how you can randomize the items of a list in place in Python?

Consider the example:

from random import shuffle
x = ['Anybody', 'Can', 'Code', 'in', 'Python']
shuffle(x)
print(x)

Output:

['Anybody', 'Code', 'in', 'Python', 'Can']

What is the use of help() function?

In Python, the help() method displays the documentation and permits you to see help related to keywords, attributes, modules etc.

What is meant by python literals?

In Python, literals can be defined as data types which are used to define variables or constants. There are three primary literals in Python:

  1. String literals: Used to define string type data. String literals are enclosed in double-quotes. For example “Amara”, “1726”.
  2. Boolean literals: These literals are used to define Boolean values, either True or False.
  3. Numeric Literals: These are numbers either int or float values. For example, 1,37,193, 2983.54 etc.
  4. How can you add a comment in a Python code?

You can add comments in Python using #. For example,

#This is a comment.

What is the use of the capitalize method in Python?

In Python, you can use the capitalize() method to convert the first letter of a string to Upper case. In case the first letter of the string is already a capital letter, then the original string is returned.

What are docstrings in Python?

In Python, docstrings stand for documentation strings. They are not comments, but because they are not assigned to any variable, they can serve the purpose of comments. Docstrings are written within triple quotes.

" " "
This is a docstring, and it can act as a comment
" " "

What are python membership operators?

In Python, the membership operators are used to check whether a given sequence is present in an object or not. There are two membership operators in Python.

  1. in: This operator returns true if the sequence is present.

Syntax: x in y

  1. not in: This operator returns true if the sequence is not present.

Syntax: x not in y

my_list = [1,2,3,4,5] 
print(5 in list1) #True
print(12 not in list) #True

Output:

True
True

What is a dictionary in Python?

In Python, dictionaries are data structures used to store data in a set of (key, value) pairs. It is an unordered collection. It defines a one-to-one relationship between entities that are indexed as keys. Each key has a corresponding value.

thisdict = {
"name": "Ananya",
"roll_no.": 185001,
"grade": A
}

How many keywords are there in Python?

In Python, there are 33 keywords; each keyword is case-sensitive. All the keywords in Python must be written only in lowercase except for three keywords. True, False and None.

Python Interview Questions 12

 

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments