Python Interview Questions
Python Interview Questions
1. What is Python?
Python is an interpreted language. It is not a hybrid language, like languages that combine
elements of both compiled and interpreted languages. In Python, the code is executed line by
line by the Python interpreter.
4. What is pep 8?
PEP in Python stands for Python Enhancement Proposal. It comprises a collection of
guidelines that outline the optimal approach for crafting and structuring Python code to
ensure the utmost clarity and legibility.
For example, in Python, the following code line will run without any error:
1a = 100
2a = "Intellipaat"
7. What is PYTHONPATH?
In Python, modules are like standalone files that house specific code components such as
functions and variables. On the other hand, libraries are essentially vast collections of
modules, and they come with pre-built functions and tools tailored for specific tasks or
domains. These libraries not only simplify the development process but also enhance
Python’s capabilities by providing readily available solutions for various programming
challenges.
The Local Namespace is specific to a function and contains the names defined
within that function. It is created temporarily when the function is called and is
cleared once the function finishes executing.
The Global Namespace includes names from imported modules or packages that
are used in the current project. It is created when the package is imported into the
script and remains accessible throughout the script’s execution.
The Built-in Namespace comprises the built-in functions provided by Python’s
core, as well as specific names dedicated to various types of exceptions.
Python embraces the principles of object-oriented programming and allows classes to acquire
the characteristics of another class, a concept known as inheritance. This facilitates code
reuse, promoting efficiency. The original class from which properties are inherited is referred
to as the superclass or parent class, while the class inheriting those properties is known as the
derived or child class. Python supports various types of inheritance, including the following:
In Python classes, the reserved method init serves a similar purpose as constructors in object-
oriented programming (OOP) terminology. When a new object is created, the init method is
automatically called, initializing the object and allocating memory for it. This method can
also be utilized to set initial values for variables.
Below is an example:
1class Human:
2 def __init__(self, age):
3 self.age = age
4 def say(self):
5 print('Hello, my age is', self.age)
6h = Human(22)
7h.say()
Output:
Hello, my age is 22
Syntax:
1dict={‘Country’:’India’,’Capital’:’New Delhi’, }
A function is a segment of code that runs only when it is called. The “def” keyword is
utilized to define a specific function, as exemplified below:
1def my_function():
2 print("Hi, Welcome to Intellipaat")
3my_function() # call to the function
Output:
Hi, Welcome to Intellipaat
Number
String
Tuple
List
Dictionary
set
A local variable is a variable that is defined within a specific function and is only accessible
within that function. It cannot be accessed by other functions within the program.
In contrast, a global variable is a variable that is declared outside of any function, allowing it
to be accessed by all functions in the program
1g=4 #global variable
2def func_multiply():
3l=5 #local variable
4m=g*l
5return m
6func_multiply()
Output: 20
If you attempt to access the local variable outside the func_multiply function, you will
encounter an error.
Python offers a valuable feature that allows for the conversion of data types as needed. This
process is referred to as type conversion in Python.
Explicit Type Conversion: This type of conversion involves the user explicitly changing the
data type to the desired type.
complex(real, imag): This function is used to convert real numbers to complex numbers in
the form of complex(real, imag).
Download Python:
After opening the Start menu, search “Environment Variables” or “Edit the
system environment variables.”
Click on the “Environment Variables” button.
Find the “Path” variable in “System Variables” and click “Edit.”
Select “New” and then provide the path to your Python installation directory. It is
typically found at “C:PythonXX” (XX represents the Python version number).
Click “OK” to save the changes.
Yes, Python is a case sensitive language. In Python, it is important to note that “Function”
and “function” are distinct entities, similar to how SQL and Pascal handle them differently.
loc and iloc are two functions provided by the Pandas library in Python to access different
parts of a DataFrame. They are primarily used for selecting rows and columns.
Aspect loc iloc
Type of Label-based Integer position-based
Indexing
Input Accepts labels of rows and Accepts integer positions for rows and
columns. columns.
Slicing End label is inclusive in the End position is exclusive in the range.
range.
Subsetting Can select rows with a particular Can select rows by integer locations
label and condition. regardless of the DataFrame index.
Mixed Allows using labels for both rows Uses integer positions for both rows and
Selection and columns. columns.
Callable Supports callable functions. Also supports callable functions.
Since python is a code block based programming language, indentation is an essential aspect
of Python syntax, ensuring proper code structure. It is a method used by programming
languages to determine the scope and extent of code blocks. In Python, indentation serves this
purpose. The mandatory requirement of indentation in Python not only enforces consistent
code formatting but also enhances code readability, which is likely the reason behind its
inclusion.
The following statements assist in altering the course of execution from the regular flow,
which categorizes them as loop control statements.
Python break: This statement aids in discontinuing the loop or the statement and
transferring control to the subsequent statement.
Python continue: This statement enforces the execution of the subsequent
iteration when a particular condition is met, instead of terminating it.
Python pass: This statement allows the syntactical writing of code while
intending to bypass its execution. It is also recognized as a null operation, as no
action is taken when the pass statement is executed.
25. How to comment with multiple lines in Python?
To include a multiline comment in Python, each line should begin with the # symbol. This
practice ensures that the code is clear and easily understood.
Python is categorized as both a programming language and a scripting language, and this dual
nature is part of what makes it so versatile and popular.
As a Programming Language:
As a Scripting Language:
Python is also considered a scripting language because it is commonly used for writing small
programs, or scripts, that automate tasks in system administration, web development, data
processing, and more. The term “scripting language” is often used for languages that are
typically interpreted (rather than compiled), which is true for Python as it is executed by an
interpreter.
To retrieve an item from a sequential collection, we can simply utilize its index, which
represents the position of that specific item. Conventionally, the index commences at 0,
implying that the initial element has an index of 0, the second element has an index of 1, and
so forth.
When employing reverse indexing, we access elements from the opposite end of the
sequence. In this case, the indexing initiates from the last element, denoted by the index
number ‘-1’. The second-to-last element is assigned an index of ‘-2’, and so forth. These
negative indexes employed in reverse indexing are specifically referred to as negative
indexes.
String Literals:
String literals are created by enclosing text within either single or double quotes where
a=”apple” and a=’apple’ mean the same. They can represent any sequence of characters such
as alphabets and numbers.
Example:
“Intellipaat”
‘45879’
Numeric Literals:
Numeric literals in Python encompass three types:
Integer: Integer literals represent whole numbers without any fractional part.
Example: I = 10
Example: i = 5.2
Example: 1.73j
Boolean Literals:
Boolean literals are utilized to denote boolean values, which can only be True or False.
Example: x = True
Python iterators are objects that allow you to access elements of a collection one at a time.
They use the __iter__() and __next__() methods to retrieve the next element until there are no
more. Iterators are commonly used in for loops and can be created for custom objects. They
promote efficient memory usage and enable lazy evaluation of elements. In summary,
iterators provide a convenient way to iterate over data structures in a controlled and efficient
manner.
No. Python is a dynamically typed language, i.e., the Python Interpreter automatically
identifies the data type of a variable based on the type of value assigned.
For example:
1my_list = [2, 3, 5, 7, 11]
2squared_list = [x**2 for x in my_list] # list comprehension
Python comments are statements used by the programmer to increase the readability of the
code. With the help of the #, you can define a single comment. Another way of commenting
is to use the docstrings (strings enclosed within triple quotes).
For example:
1#Comments in Python
2print("Comments in Python ")
Functions in Python, range() and xrange(), are used to iterate inside a for loop for a fixed
number of times. Functionality-wise, both these functions are the same. The difference comes
when talking about the Python version support for these functions and their return values.
range() Method xrange() Method
In Python 3, xrange() is not supported; instead, the The xrange() function is used in Python 2
range() function is used to iterate inside for loops to iterate inside for loops
It returns a list It returns a generator object as it doesn’t
really generate a static list at the run time
It takes more memory as it keeps the entire list of It takes less memory as it keeps only one
iterating numbers in memory number at a time in memory
Tkinter is a built-in Python module that is used to create GUI applications and it is Python’s
standard toolkit for GUI development. Tkinter comes pre-loaded with Python so there is no
separate installation needed. You can start using it by importing it in your script.
Python does follow an object-oriented programming paradigm and has all the basic OOPs
concepts such as inheritance, polymorphism, and more, with the exception of access
specifiers. Python doesn’t support strong encapsulation (adding a private keyword before data
members). Although, it has a convention that can be used for data hiding, i.e., prefixing a data
member with two underscores.
For opening a text file using the above modes, we will have to append ‘t’ with them as
follows:
Similarly, a binary file can be opened by appending ‘b’ with them as follows:
To append the content in the files, we can use the append mode (a):
modules in Python?
Python comes with some file-related modules that have functions to manipulate text files and
binary files in a file system. These modules can be used to create text or binary files,
update content by carrying out operations like copy, delete, and more.
Some file-related modules are os, os.path, and shutil.os. The os.path module has functions to
access the file system, while the shutil.os module can be used to copy or delete files.
40. Explain the use of the 'with' statement and its syntax?
In Python, using the ‘with’ statement, we can open a file and close it as soon as the block of
code, where ‘with’ is used, exits. In this way, we can opt for not using the close() method.
1with open("filename", "mode") as file_var:
To display the contents of a file in reverse, the following code can be used:
1filename = "filename.txt"
2with open(filename, "r") as file:
3 lines = file.readlines()
4
5for line in reversed(lines):
6 print(line.rstrip())
Now in these Python Interview questions lets look at some python interview coding questions
1. xyz = 1,000,000
2. x y z = 1000 2000 3000
3. x,y,z = 1000, 2000, 3000
4. x_y_z = 1,000,000
Ans. Second statement is invalid. This is invalid because variable names in Python cannot
contain spaces, and multiple variables cannot be assigned in this way without commas to
separate them. Additionally, the values to be assigned are not separated by commas, making
the statement syntactically incorrect.
Command:
1f= open(“hello.txt”, “wt”)
len() is an inbuilt function used to calculate the length of sequences like list, python string,
and array.
1my_list = [1, 2, 3, 4, 5]
2length = len(my_list)
3print(length)
To remove duplicate elements from the list we use the set() function.
You need to import the OS Module and use os.remove() function for deleting a file in
python.
consider the code below:
1import os
2os.remove("file_name.txt")
For example:
1import random
2def read_random(fname):
3lines = open(fname).read().splitlines()
4return random.choice(lines)
5print(read_random('hello.txt'))
49. Write a Python program to count the total number of lines in a text file?
Refer the code below to count the total number of lines in a text file-
1def file_count(fname):
2 with open(fname) as f:
3 for i, _ in enumerate(f):
4 pass
5 return i + 1
6
7print("Total number of lines in the text file:",
8file_count("file.txt"))
50. What would be the output if I run the following code block?
1list1 = [2, 33, 222, 14, 25]
2print(list1[-2])
1. 14
2. 33
3. 25
4. Error
Ans. output:14
In Python, negative indexing allows you to access elements from the end of the list. The
index -1 represents the last element, -2 represents the second-to-last element, and so on.
In the given code, list1[-2] refers to the second-to-last element in the list list1, which is 14.
Therefore, the output of the code will be 14.
Operators are referred to as special functions that take one or more values (operands) and
produce a corresponding result.
is: returns the true value when both the operands are true (Example: “x” is ‘x’)
not: returns the inverse of the boolean value based upon the operands
(example:”1” returns “0” and vice-versa.
In: helps to check if the element is present in a given Sequence or not.
The ternary operator is the operator that is used to show conditional statements in Python.
This consists of the boolean true or false values with a statement that has to be checked.
Syntax:
1x , y=10,20
2count = x if x < y else y
Explanation:
If the condition x < y is true, then the value of x is assigned to count. This means that if the
value of x is less than the value of y, count will be equal to x.
If the condition x < y is false, then the value of y is assigned to count. This means that if the
value of x is not less than the value of y, count will be equal to y.
In python, adding elements in an array can be easily done with the help
of extend(),append() and insert() functions.
Consider the following example:
1x=arr.array('d', [11.1 , 2.1 ,3.1] )
2x.append(10.1)
3print(x) #[11.1,2.1,3.1,10.1]
4x.extend([8.3,1.3,5.3])
5print(x) #[11.1,2.1,3.1,10.1,8.3,1.3,5.3]
6x.insert(2,6.2)
7print(x) # [11.1,2.1,6.2,3.1,10.1,8.3,1.3,5.3]
54. What is the procedure for deleting values from a Python array?
Elements can be removed from a python array by using pop() or remove() methods.
Output:
13.6
21.1 # element popped at 3 rd index
3array('d', [ 2.4, 6.8, 7.7, 1.2])
To reverse a list in Python, you can use the slicing technique. Here’s a brief explanation of
the process:
Assign the reversed list to a new variable or overwrite the original list with the reversed
version.
original_list = [1, 2, 3, 4, 5]
reversed_list = original_list[::-1]
57. How will you remove the last object from a list in Python?
1my_list = [1, 2, 3, 4, 5]
2my_list.pop()
Here, −1 represents the last element of the list. Hence, the pop() function removes the last
object (obj) from the list.
This is achieved by importing the random module. It is the module that is used to generate
random numbers.
Syntax:
1import random
2random.random # returns the floating point random number between the range of [0,1].
To convert a string to all lowercase in Python, you can use the built-in lower() method. The
lower() method is available for strings and returns a new string with all characters converted
to lowercase.
For Example:
1demo_string='ROSES'
2print(demo_string.lower())
60. Why would you use NumPy arrays instead of lists in Python?
NumPy arrays provide users with three main advantages as shown below:
NumPy arrays consume a lot less memory, thereby making the code more
efficient.
NumPy arrays execute faster and do not add heavy processing to the runtime.
NumPy has a highly readable syntax, making it easy and convenient for
programmers.
Polymorphism in Python is the ability of the code to take multiple forms. Let’s say, if the
parent class has a method named XYZ then the child class can also have a method with the
same name XYZ having its own variables and parameters.
Encapsulation in Python refers to the process of wrapping up the variables and different
functions into a single entity or capsule. The Python class is the best example of
encapsulation in python.
63. What benefits do NumPy arrays provide compared to (nested) Python lists?
Nested Lists:
Numpy:
NumPy is more efficient and more convenient as you get a lot of vector and
matrix operations for free, this helps avoid unnecessary work and complexity of
the code. NumPy is also efficiently implemented when compared to nested lists.
NumPy array is faster and contains a lot of built-in functions which will help in
FFTs, convolutions, fast searching, linear algebra,basic statistics, histograms,etc.