Top 30 Interview Questions Answers on Python

1.What is Python?

Python is a high-level, interpreted programming language with easy-to-read syntax. It is an open-source language that is used for a wide range of tasks such as web development, data analysis, artificial intelligence, and scientific computing.

2. What are the advantages of using Python?

Python has several advantages over other programming languages, including:

  • Easy-to-learn syntax
  • Large standard library
  • Object-oriented programming
  • Cross-platform compatibility
  • Support for third-party modules and packages
  • Interpreted language, no compilation needed
  • Automatic memory management

3. What are the different data types in Python?

Python has several built-in data types, including:

  • Numbers (int, float, complex)
  • Strings
  • Lists
  • Tuples
  • Dictionaries
  • Sets

4.What is the difference between a list and a tuple in Python?

A list is a mutable sequence of elements, while a tuple is an immutable sequence of elements. This means that once a tuple is created, its elements cannot be changed, whereas the elements of a list can be changed.

5.What is a dictionary in Python?

A dictionary is an unordered collection of key-value pairs. Each key in a dictionary must be unique, and it is used to access its corresponding value.

6.What is the difference between Python 2 and Python 3?

Python 2 and Python 3 are two different versions of the Python programming language. The key differences between them are:

  • Python 2 uses print statement without parentheses, while Python 3 uses print function with parentheses.
  • Python 2 has a different division operator (/), which returns an integer if both operands are integers, while Python 3 uses true division (/), which always returns a float.
  • Python 3 has more consistent Unicode handling than Python 2.
  • Python 2 has more mature libraries and frameworks, while Python 3 has better support for modern web standards.

7. What are decorators in Python?

Decorators are a way to modify or enhance the behavior of a function or class without changing its source code. They are functions that take another function as input, modify it, and return it as output.

8. What is a lambda function in Python?

A lambda function is an anonymous function in Python that can take any number of arguments but can only have one expression. They are commonly used for simple, one-line functions that do not require a name.

9.What is the difference between a deep copy and a shallow copy in Python?

A shallow copy creates a new object that references the same memory as the original object. This means that changes to the new object will affect the original object. A deep copy creates a new object and recursively copies all the objects referenced by the original object, so changes to the new object will not affect the original object.

10. How do you handle exceptions in Python?

In Python, exceptions are handled using try-except blocks. The code that might raise an exception is placed in the try block, and the code that handles the exception is placed in the except block. If an exception is raised in the try block, the code in the except block is executed.

11.What is the difference between .py and .pyc files?

The .py files are the python source code files. While the .pyc files contain the bytecode of the python files. .pyc files are created when the code is imported from some other source. The interpreter converts the source .py files to .pyc files which helps by saving time. You can get a better understanding with the Data Engineering Course in Washington.

12.What is slicing in Python?

Slicing is used to access parts of sequences like lists, tuples, and strings. The syntax of slicing is-[start:end:step]. The step can be omitted as well. When we write [start:end] this returns all the elements of the sequence from the start (inclusive) till the end-1 element. If the start or end element is negative i, it means the ith element from the end. The step indicates the jump or how many elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]. Then [-1:2:2] will return elements starting from the last element till the third element by printing every second element.i.e. [8,6,4].

13.What are Keywords in Python?

Keywords in python are reserved words that have special meaning.They are generally used to define type of variables. Keywords cannot be used for variable or function names. There are following 33 keywords in python-

  • And
  • Or
  • Not
  • If
  • Elif
  • Else
  • For
  • While
  • Break
  •  As
  • Def
  • Lambda
  • Pass
  • Return
  • True
  • False
  • Try
  • With
  • Assert
  • Class
  • Continue
  • Del
  • Except
  • Finally
  • From
  • Global
  • Import
  • In
  • Is
  • None
  • Nonlocal
  • Raise
  • Yield

14.What are Literals in Python and explain about different Literals

A literal in python source code represents a fixed value for primitive data types. There are 5 types of literals in python-

  1. String literals– A string literal is created by assigning some text enclosed in single or double quotes to a variable. To create multiline literals, assign the multiline text enclosed in triple quotes. Eg.name=”Tanya”
  2. A character literal– It is created by assigning a single character enclosed in double quotes. Eg. a=’t’
  3. Numeric literals include numeric values that can be either integer, floating point value, or a complex number. Eg. a=50
  4. Boolean literals– These can be 2 values- either True or False.
  5. Literal Collections– These are of 4 types-

a) List collections-Eg. a=[1,2,3,’Amit’]

             b) Tuple literals- Eg. a=(5,6,7,8)

c) Dictionary literals- Eg. dict={1: ’apple’, 2: ’mango, 3: ’banana`’}

d) Set literals- Eg. {“Tanya”, “Rohit”, “Mohan”}

6. Special literal- Python has 1 special literal None which is used to return a null variable.

15.How to combine dataframes in pandas?

The dataframes in python can be combined in the following ways-

  1. Concatenating them by stacking the 2 dataframes vertically.
  2. Concatenating them by stacking the 2 dataframes horizontally.
  3. Combining them on a common column. This is referred to as joining.

The concat() function is used to concatenate two dataframes. Its syntax is- pd.concat([dataframe1, dataframe2]).

Dataframes are joined together on a common column called a key. When we combine all the rows in dataframe it is union and the join used is outer join. While, when we combine the common rows or intersection, the join used is the inner join. Its syntax is- pd.concat([dataframe1, dataframe2], axis=’axis’, join=’type_of_join)

16.What are the new features added in Python 3.9.0.0 version?

The new features in Python 3.9.0.0 version are-

  •  New Dictionary functions Merge(|) and Update(|=)
  • New String Methods to Remove Prefixes and Suffixes
  • Type Hinting Generics in Standard Collections
  • New Parser based on PEG rather than LL1
  • New modules like zoneinfo and graphlib
  • Improved Modules like ast, asyncio, etc.
  • Optimizations such as optimized idiom for assignment, signal handling, optimized python built ins, etc.
  • Deprecated functions and commands such as deprecated parser and symbol modules, deprecated functions, etc.
  • Removal of erroneous methods, functions, etc.

17.How is memory managed in Python?

Memory is managed in Python in the following ways:

  1. Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.
  2. The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.
  3. Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.

18. What is namespace in Python?

A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.

Course Curriculum

Data Science with Python Certification Course

Explore Curriculum

19. What is PYTHONPATH?

It is an environment variable which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.

20. What are python modules? Name some commonly used built-in modules in Python?

Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code.

Some of the commonly used built-in modules are:

  • os
  • sys
  • math
  • random
  • data time
  • JSON

21.What are local variables and global variables in Python?

Global Variables:

Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.

Local Variables:

Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.

Example:

123456a=2defadd():b=3c=a+bprint(c)add()

Output: 5

When you try to access the local variable outside the function add(), it will throw an error.

22. Is python case sensitive?

 Yes. Python is a case sensitive language.

23.What is type conversion in Python?

Ans: Type conversion refers to the conversion of one data type into another.

int() – converts any data type into integer type

float() – converts any data type into float type

ord() – converts characters into integer

hex() – converts integers to hexadecimal

oct() – converts integer to octal

tuple() – This function is used to convert to a tuple.

set() – This function returns the type after converting to set.

list() – This function is used to convert any data type to a list type.

dict() – This function is used to convert a tuple of order (key, value) into a dictionary.

str() – Used to convert integer into a string.

complex(real,imag) – This function converts real numbers to complex(real,imag) number.

24. How to install Python on Windows and set path variable?

 To install Python on Windows, follow the below steps:

  • Install python from this link: https://www.python.org/downloads/
  • After this, install it on your PC. Look for the location where PYTHON has been installed on your PC using the following command on your command prompt: cmd python. 
  • Then go to advanced system settings and add a new variable and name it as PYTHON_NAME and paste the copied path.
  • Look for the path variable, select its value and select ‘edit’.
  • Add a semicolon towards the end of the value if it’s not present and then type %PYTHON_HOME% 

25. Is indentation required in python?

Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.

26. What is the difference between Python Arrays and lists?

Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type elements whereas lists can hold any data type elements.

Example:

12345importarray as arrMy_Array=arr.array('i',[1,2,3,4])My_list=[1,'abc',1.20]print(My_Array)print(My_list)

Output:

array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]

27. What are functions in Python?

A function is a block of code which is executed only when it is called. To define a Python function, the def keyword is used.

Example:

123defNewfunc():print("Hi, Welcome to Edureka")Newfunc(); #calling the function

Output: Hi, Welcome to Edureka

28.What is __init__?

__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.

Here is an example of how to use it.

1234567891011classEmployee:def__init__(self, name, age,salary):self.name =nameself.age =ageself.salary =20000E1 =Employee("XYZ", 23, 20000)# E1 is the instance of class Employee.#__init__ allocates memory for E1. print(E1.name)print(E1.age)print(E1.salary)

Output:

XYZ

23

20000

29.What is a lambda function?

An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.

Example:

12a =lambdax,y : x+yprint(a(5, 6))

Output: 11

30. What is self in Python?

Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional.  It helps to differentiate between the methods and attributes of a class with local variables.

The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.

Top 30 Interview Questions Answers on Python
Show Buttons
Hide Buttons