0 ratings 0% found this document useful (0 votes) 20 views 84 pages Python Interview Question and Answer
The document provides a comprehensive guide to the top 100 Python interview questions and answers, covering various aspects of the language. It is designed to help both beginners and experienced developers prepare for job interviews by explaining concepts clearly with examples. Topics include Python's features, data types, functions, and control flow, making it a valuable resource for anyone looking to enhance their Python knowledge.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Carousel Previous Carousel Next
Save Python Interview question and answer For Later Top 100 Python Interview Questions
and Answers
here we discuss questions regarding all aspects that are mostly asked
in Python Interviews
Top 100
Python
Interview
Questions
and Answers
O71825, 8:96 AM op 100 Python interview Questions and Answers | by Sirsh Shukla | Medium
Python is one of the most popular programming languages in the world
today. It is known for its simple and readable syntax, making it a great choice
for beginners as well as experienced developers. Python is used in many
areas of technology, including web development, data science, machine
learning, automation, artificial intelligence, game development, and more.
Because of its wide usage, Python is a common topic in job interviews for
software developers, data analysts, machine learning engineers, and other
tech roles. Whether you're a fresher preparing for your first job, or a
professional looking to switch careers, understanding the most common
Python interview questions can help you feel more confident and perform
better.
In this guide, we have gathered the top 100 Python interview questions and
answers, starting from the basics and moving to more advanced topics. Each
answer is written in simple words and explained clearly with examples so
that anyone can understand — even if you're just starting your Python
journey.
Let's dive into the questions and get ready to ace your Python interview!
1. What is Python?
Python is a popular, high-level programming language that is easy to read
and write. It was created by Guido van Rossum and released in 1991. One of
the main reasons why Python is so widely used is because of its simple
syntax that looks like English. This makes it a great choice for beginners.
Python is also versatile — you can use it for web development, data science,
artificial intelligence, machine learning, automation, scripting, and more. It
is free to use and open-source, which means anyone can download and use
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 2188“2, 8:9 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
it. Big companies like Google, Instagram, and Netflix use Python in their
systems.
2. What are the key features of Python?
Python has many features that make it a popular choice among developers.
First, it is easy to learn and use. The syntax is simple, which helps beginners
write code quickly. Second, it is an interpreted language, meaning Python
executes code line by line, which makes debugging easier. Python is cross-
platform, so it works on Windows, Mac, and Linux. It also supports object-
oriented and functional programming. Another great feature is its huge
standard library — it includes many tools and modules to do different tasks
without writing everything from scratch. Python also has a large community,
so getting help and learning resources is easy.
3. What are variables in Python?
Variables in Python are used to store information that you want to use later.
Think of a variable as a box where you can keep something, like a number or
aname. You don’t need to mention the data type when creating a variable —
Python figures it out. For example:
name = "Alice"
age = 25
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 ies71825, 8:96 AM op 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
Here, name stores a string and age stores an integer. You can also change the
value of a variable anytime. Variables make it easy to write flexible programs
where data can change. You just use the variable name wherever you need
that value in your code.
4. What are data types in Python?
Data types tell Python what kind of value a variable holds. For example, int
is for whole numbers, float is for decimal numbers, and str is for text.
Python also has boot for True or False values, List for a collection of items,
tuple for an unchangeable group of items, dict for key-value pairs, and set
for unique items. These types help Python decide what kind of operations
can be done with the data. You don't have to define the type—Python does it
automatically. Knowing data types is important to avoid errors and to use
functions correctly in your code.
5, Whatis a list in Python?
A list in Python is a collection of items that are ordered and changeable. Lists
are written with square brackets like this:
fruits = ["apple", "banana", "cherry"
You can add, remove, or change items in a list using functions like append() ,
remove() , or by using indexes like fruits[1] = "orange" . Lists can contain
bitpsi/shirsh8¢.macium.convtop-100-pythor-nterview-questions-and.answors-4e403301ASb6 418471825, 8:96 AM op 100 Python interview Questions and Answers | by Sirsh Shukla | Medium
different data types—numbers, strings, even other lists. They are useful
when you want to store multiple items in one variable. You can also loop
through a list using a for loop. Lists are one of the most used data structures
in Python because they are simple and powerful.
6. What is a tuple in Python?
A tuple is similar to a list, but the key difference is that you cannot change
the items in a tuple once it is created. Tuples are immutable, which means
unchangeable. They are written with parentheses like this:
colors = ("red", "green", "blue")
You can access items in a tuple using an index like colors[o] . Tuples are
useful when you want to make sure that the data does not change. They are
also slightly faster than lists. Tuples can be used as keys in dictionaries, but
lists cannot because they are mutable. So, if you want to store fixed data,
tuples are a good choice.
'7. What is a dictionary in Python?
A dictionary in Python stores data in key-value pairs. Each key is linked to a
value, like a word and its meaning in a real dictionary. Dictionaries are
written using curly braces:
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 sie‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
person = {"name": "Alice", "age": 30}
You can access the value by using the key: person{"name"] returns "Alice".
You can also add new key-value pairs or update existing ones. Dictionaries
are very useful when you need to store related information, like user details
or configuration settings. Keys must be unique and immutable, like strings
or numbers. Dictionaries are fast and great for looking up data by name or
key.
8. What is a set in Python?
Aset in Python is a collection of unique items. It is unordered, which means
the items do not have a fixed position. Sets are written using curly braces:
numbers = {1, 2, 3, 2}
The set automatically removes duplicates, so the output will be {1, 2, 3}.
Sets are useful when you want to remove duplicates or check for common
values between groups using operations like union, intersection, and
difference. Since sets are unordered, you cannot access items using indexes.
Sets are also faster than lists when checking if an item exists. They are
simple but powerful for handling unique data.
bitpsi/shirsh8¢.macium.convtop-100-pythor-nterview-questions-and.answors-4e403301ASb6 ies‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
9. What is the difference between list and tuple in Python?
Both lists and tuples can store multiple items, but they have some key
differences. Lists are mutable, which means you can change, add, or remove
items after the list is created. Tuples are immutable, which means you
cannot change them after they are made. Lists are written with square
brackets [ ], while tuples use parentheses ( ) . Because of immutability,
tuples are faster and can be used as keys in dictionaries, while lists cannot.
Use a list when your data might change. Use a tuple when your data should
stay the same. Both are useful in different situations.
10. How do you write comments in Python?
Comments in Python are used to explain what your code is doing. Python
ignores comments — they are just for humans reading the code. To write a
single-line comment, start the line with #:
# This is a single-line comment
You can also write multi-line comments using triple quotes:
This is a
multi-line comment
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 78411905, 83486 Top 100 Fytenmtrvew Questons and Anawer by Shes Shute | edu
Good comments help others (and yourself) understand your code, especially
when it’s long or complex. They make your code more readable and easier to
Openinapo * : Gas) Sionin
Medium = searen (F write
11. How is Python interpreted?
Python is an interpreted language, which means the code is not compiled
before running. Instead, it is executed line-by-line by the Python interpreter.
When you write Python code and run it, the interpreter reads each line,
translates it into machine language, and then executes it immediately. This is
different from compiled languages like C or Java, where the code is turned
into a complete executable file before it runs. Being interpreted makes it
easier to test and debug Python code. If there’s an error, Python will stop at
that line and show an error message. This feature is great for beginners and
for rapid development.
12. What is indentation in Python and why i:
it important?
Indentation in Python refers to the spaces or tabs at the beginning of a line.
Unlike many other programming languages, Python uses indentation to
define blocks of code. For example, in loops, conditionals, and functions, the
indented lines belong to the same code block. If indentation is not done
correctly, Python will raise an error and stop running. This makes Python
code more readable and clean. Here is a simple example:
tpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4e40930 1306 ares‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
if 5 > 2:
print("Five is greater than two")
In the above code, the print statement is indented, which shows that it
belongs to the if block. Proper indentation is very important in Python
programming.
13. What are Python functions?
A function in Python is a block of reusable code that performs a specific
task. You can define your own functions using the det keyword, or you can
use built-in functions like print() , len() , and type() . Functions help you
avoid repeating code and make your programs more organized. Here's an
example of a simple function:
def greet (name):
print("Hello, " + name)
You can call this function like greet ("Alice") . Functions can take
parameters and can also return values using the return keyword. Using
functions makes your code shorter, cleaner, and easier to manage.
14. What is the difference between a function and a method in Python?
tpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4e40930 1306 ies11905, 83486 Top 100 Fytenmtrvew Questons and Anawer by Shes Shute | edu
In Python, a function is a block of code that performs a task and is defined
using the det keyword. It can be used on its own, outside of any class. For
example:
def add(a, b):
return a+b
A method, on the other hand, is a function that is associated with an object.
Methods are defined inside classes and are called using dot notation. For
example:
name = "Alice"
print(name.upper()) # upper() is a method
In simple terms, all methods are functions, but not all functions are
methods. Methods always belong to an object or class, while functions do
not.
15. What are arguments and parameters in Python functions?
Parameters are the names you define in a function when you write it.
Arguments are the actual values you pass to the function when calling it. For
example:
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 1018‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
def greet(name): # ‘name’ is a parameter
print("Hello, " + name)
greet("Alice") # "Alice" is the argument
In this case, name is a parameter, and "Alice" is the argument passed to the
function. Python also supports default arguments, keyword arguments, and
variable-length arguments. Understanding how parameters and arguments
work is important for writing flexible and reusable functions.
16. What is the use of the return statement in Python?
The return statement in Python is used in a function to send a value back to
the place where the function was called. It ends the function and passes the
result to the caller. Here's an example:
def add(a, b):
return a+b
result = add(5, 3)
print(result) # Output: 8
In this case, the function add returns the sum of a and b, which is then
stored in the variable result. If there is no return statement, the function
bitpsi/shirsh8¢.macium.convtop-100-pythor-nterview-questions-and.answors-4e403301ASb6 ‘88‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
will return None by default. Using return makes functions more useful
because they can provide output to be used later.
17. What is the difference between de1 and remove() inPython?
In Python, both det and remove() are used to delete elements, but they
operate differently and are used in different contexts.
* The del statement is a language construct used to delete an item ata
specific index from a list or to delete entire variables or slices. It works
with all types of objects, including lists, dictionaries, and variables. For
example:
nums = [1, 2, 3, 4] del nums[1] # removes the item at index 1 (value 2)
The remove() method, on the other hand, is a list method that removes
the first occurrence of a specific value from the list. It raises a
valuetrror if the item is not found:
nums = [1, 2, 3, 2]
nums.remove(2) # removes the first 2
In summary, use det when you know the index or want to delete a variable.
Use remove() when you want to delete a known value from a list.
bitpsi/shirsh8¢.macium.convtop-100-pythor-nterview-questions-and.answors-4e403301ASb6 1218‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
18. What is the difference between for and while loops in Python?
The for loop and white loop are both used to repeat actions, but they are
used in different situations. A for loop is best when you know in advance
how many times you want to repeat something. It works well with lists,
strings, and ranges:
for i in range(5):
print(i)
A white loop is better when you don't know how many times you'll repeat
and want to continue until a certain condition is false:
while i <5:
print(i)
fea
So, use for when looping through known items, and use while when you
need to loop based on a condition.
19. What is a conditional statement in Python?
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 13184‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
Conditional statements are used to run certain blocks of code only when
specific conditions are met. Python uses if, elif, and else for this:
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
You can also use etif (short for “else if") to check multiple conditions:
if score >= 96:
print("A grade")
elif score >= 75:
print("B grade")
else:
print("C grade")
Conditional statements help your programs make decisions and behave
differently based on input or data.
20. What is the use of the break, continue, and pass statements in Python?
These three statements control how loops behave:
* break: Stops the loop entirely and exits:
tpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4e40930 1306 14ina‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
for i in range(s):
if iss 3:
break
print(i) # Prints 0, 1, 2
* continue : Skips the current loop cycle and moves to the next one:
for i in range(5):
if iss 3:
continue
print(i) # Skips 3
* pass: Does nothing. It’s used as a placeholder where code is needed later:
for 4 in range(S):
pass # To be implemented later
These are useful for controlling loops more precisely based on your
program's needs.
21. What are Python lists and how do you use them?
A list in Python is a collection of items that can hold different types of values
like numbers, strings, or even other lists. Lists are ordered and changeable,
tpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4e40930 1306 1518411905, 83486 Top 100 Fytenmtrvew Questons an Anawer by Shes Shute | edu
meaning you can update, add, or remove items. You define a list using
square brackets:
fruits = ["apple", "banana", "cherry"]
You can access list items by index, like fruitste] which gives "apple" . You
can also change values, like fruits(1] = "orange" . Python lists have many
useful functions like append() to add anitem, remove() to delete an item,
and sort() to sort the list. Lists are one of the most used data types in
Python.
22. What is the difference between alist and a tuple in Python?
Both lists and tuples are used to store multiple items, but the main
difference is that lists are mutable (changeable), while tuples are immutable
(cannot be changed). You create a list with square brackets [] , anda tuple
with parentheses ():
my_list = (1, 2, 3]
my_tuple = (1, 2, 3)
You can change my_list[o] = 10, but you cannot change my_tuptefo] . Tuples
are faster and take up less memory than lists. Use tuples when your data
bitpsi/shirsh8¢.macium.convtop-100-pythor-nterview-questions-and.answors-4e403301ASb6 1618411905, 83486 Top 100 Fytenmtrvew Questons and Anawer by Shes Shute | edu
should not change, such as coordinates or fixed settings. Lists are better
when you need to update, sort, or modify the data.
23. What are Python dictionaries and how are they used?
A dictionary in Python is a collection of key-value pairs. Each key is unique
and maps to a value. You create a dictionary using curly braces {}:
person = {"name": "Alice", "age": 25}
You can access values using keys, like person["name"] which gives "Alice" .
You can also add or update values, like person[("age"] = 30. Dictionaries are
useful when you want to store and retrieve data using names or identifiers
instead of positions. Some helpful functions include keys() , values() , and
itens() . They are powerful for storing structured data, like JSON responses
or configuration settings.
24. What are Python sets and what are they used for?
A set is a collection of unique items. It is unordered, so the items do not have
a fixed position and cannot be accessed by index. Sets are defined using
curly braces ():
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 17188‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
my_set = {1, 2, 3}
If you try to add a duplicate, it will be ignored. Sets are useful for checking
membership and removing duplicates. You can use add() to insert elements
and renove() to delete them. Python also supports set operations like union
(|), intersection («), and difference ( - ). Sets are great when you need fast
lookups or want to ensure no duplicates exist.
25. How do you create a class in Python?
Aclass in Python is a blueprint for creating objects. It defines the structure
and behavior (methods and variables) of an object. You create a class using
the class keyword:
class Person:
def _init_(self, name):
self.name = name
def greet(self):
print("Hello, my name is " + self.name)
The __init__ method is the constructor and runs when a new object is
created. You can create an object like p1 = person("alice") and call its
method using p1.greet() . Classes help in object-oriented programming and
allow you to create reusable code.
tpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4e40930 1306 16184‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
26. What is an object in Python?
‘An object in Python is an instance of a class. When you create a class, you're
just defining the structure. But when you create an object using that class,
you get a working version with real values. For example:
class Dog:
def __init__(self, name):
self.name = name
dogl = Dog("Buddy")
Here, dog: is an object of the bog class. It has its own copy of data and can
use class methods. In Python, almost everything is an object—strings, lists,
functions, and even classes. Objects make code modular, reusable, and
organized.
27. What is inheritance in Python?
Inheritance in Python allows one class (called a child or subclass) to get
features from another class (called a parent or base class). It helps in reusing
code and building relationships between classes. Here’s a basic example:
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 19184‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal) :
def bark(self) :
print("Dog barks")
d = Dog()
d.speak()
d.bark()
In this example, the bog class inherits from Animal, so it can use the speak()
method. Inheritance supports code reuse and helps organize code better
when working with related classes.
28. What is polymorphism in Python?
Polymorphism means “many forms”. In Python, polymorphism allows
different classes to have methods with the same name, but different
behavior. For example, if two classes have a method named speak() , you can
call speak() on any object, and it will behave according to its class:
class Dog:
def speak(self):
return "Bark"
class Cat:
def speak(self
return "Meow'
bitpsi/shirsh8¢.macium.convtop-100-pythor-nterview-questions-and.answors-4e403301ASb6 20184‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak())
Each object knows how to perform its version of the method. Polymorphism
makes code flexible and helps when writing functions that can work with
multiple types of objects.
29, What is encapsulation in Python?
Encapsulation is a concept in object-oriented programming that hides the
internal details of a class and protects data from outside access. In Python,
we use private variables (with a single or double underscore _ or __) to
indicate that they should not be accessed directly:
class Person:
def _init__(self, name):
self.__name = name # private variable
def get_name(self) :
return self.__name
In this example, __name is private. We access it using the get_name() method.
Encapsulation helps keep your data safe, and only allows access through
defined methods, making your code more secure and easier to maintain.
tpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4e40930 1306 21184‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
30. What is abstraction in Python?
Abstraction means showing only the essential features and hiding the
unnecessary details. It helps reduce complexity and allows you to focus on
what an object does, not how it does it. In Python, abstraction is often
implemented using abstract classes and methods from the abc module:
from abe import ABC, abstractmethod
class Animal (ABC) :
@abstractmethod
def make_sound(self) :
pass
class Dog(Animal) :
def make_sound(self) :
print ("Bark")
Here, Animal is an abstract class, and make_sound() must be implemented in
any child class. Abstraction helps in designing clean interfaces and focusing
on high-level functionality.
31. What is the difference between «args and «*kwargs in Python?
* xargs allows a function to accept any number of positional arguments,
packed as a tuple.
+ +xkwargs allows a function to accept any number of keyword arguments,
packed as a dictionary.
tpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4e40930 1306 aie‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
Example:
def deno(sargs, r*kwargs):
print (ares)
print (kwargs)
demo(1, 2, a=3, b=4)
These are useful for creating flexible functions, wrappers, and decorators.
32.Whatis the if __name__ == "__main__" statement used for?
The if __name__ == "__main__" statement is used to control the execution of
code in Python scripts. When a Python file is run directly, the special built-in
variable __name__ is set to "__main__" . However, when that file is imported as
a module into another script, __name__ is set to the module's name instead.
This allows developers to write code that acts differently depending on
whether it’s run directly or imported. It’s commonly used to encapsulate the
script’s entry point:
def main():
print("Running as a script")
if __name_,
main()
tpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4e40930 1306 2318411905, 83486 Top 100 Fytenmtrvew Questons and Anawer by Shes Shute | edu
This is particularly useful in larger applications and during unit testing, as it
allows for better organization and reuse of code.
33. What isa cefauitdict inPython?
A defaultdict is a subclass of the built-in dict class that provides a default
value for non-existent keys. This prevents Keyérror exceptions and is
particularly useful when counting items or grouping data.
It requires a factory function to specify the default value:
from collections import defaultdict
dd = defaultdict (int)
dd["apple"] +5 1 # no error even though "apple" didn't exist
This is much cleaner than checking for key existence manually using get()
or if statements. Common factories include int, list, and set.
34. What is list comprehension in Python?
List comprehension is a concise way to create lists in Python. Instead of
using loops, you can use a single line of code. It improves readability and
performance. Here’s a basic example:
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 area‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
squares = [x#x for x in range(5)]
This creates alist [o, 1, 4, 9, 16] . You can also add conditions:
even = [x for x in range(10) if x % 2 == 6]
List comprehensions are useful when you want to transform or filter data
quickly. They make your code shorter, cleaner, and easier to understand than
using a full for loop.
35. What is a higher-order function in Python?
A higher-order function is any function that either accepts another function
as an argument, or returns a function as its result. Python supports higher-
order functions natively, which makes it a flexible language for functional-
style programming.
Examples of built-in higher-order functions in Python include map() ,
filter() , and sorted() .
Example:
def apply_twice(func, value):
return func(func(value) )
Pitpss/shiesh8¢.macium.convtop-100-pythor ntervew-questions-and.answors-4c409301ASb6 25184‘18/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
def square(x):
return x * x
print(apply_twice(square, 2)) # Output: 16
Higher-order functions promote reusability and abstraction, allowing more
expressive and concise code.
36. How does Python handle memory management?
Python manages memory automatically using a system called garbage
collection. This system keeps track of all objects and frees up memory that is
no longer being used. Python also uses reference counting — each object
keeps a count of how many references point to it. When that count reaches
zero, the memory is released. Python’s memory management is done by the
Python memory manager, and it includes private heap space where all
objects and data structures are stored. As a developer, you don’t usually need
to manage memory directly, but understanding how it works can help write
better, more efficient code.
37. What is multiple inheritance in Python?
Multiple inheritance is when a class inherits from more than one parent
class. Python fully supports this, which allows a class to combine
functionality from multiple sources.
Example:
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 26184‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
class A:
def greet(self):
print("Hello from a")
class B:
def greet(self) :
print("Hello from 8")
class C(A, B):
pass
c= C0
c.greet() # Uses A's method due to MRO
While powerful, multiple inheritance can make the class hierarchy hard to
manage, so it should be used with care. The super() function and MRO help
mitigate the complexity.
38. What is a package in Python?
A package in Python is a collection of modules organized in directories. It
allows you to group related modules together. A package is a folder that
contains an __init__.py file, which tells Python that the folder should be
treated as a package. Example structure:
mypackage/
|
JK _init_.py
JK modutei.py
LL module2.py
You can import modules from the package using dot notation:
bitpsi/shirsh8¢.macium.convtop-100-pythor-nterview-questions-and.answors-4e403301ASb6 78a‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
from mypackage import moduled
Packages help in organizing large applications and reusing code across
projects. Python also has many third-party packages that can be installed
using tools like pip.
39. What is the purpose of __init__.py in Python packages?
The __init__.py file in Python marks a directory as a package so that its
modules can be imported. Without this file, Python won't recognize the
folder as a package in older versions (though in modern Python, it’s
optional). This file can be empty or contain initialization code for the
package. For example, you might import key modules or define variables
inside it:
# init__.py
from .modulel import functiont
With this, users can simply do from package import functioni instead of
importing the whole module, It helps organize imports and controls how
packages behave during import.
bitpsi/shirsh8¢.macium.convtop-100-pythor-nterview-questions-and.answors-4e403301ASb6 28184‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
40. How do you handle exceptions in Python?
In Python, you handle errors and exceptions using try, except, and
optionally finatty . This allows your program to continue running even if
something goes wrong. Here's an example:
try:
num = intCinput ("Enter a number:
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number.")
Finally:
print("This always runs.")
The try block runs the risky code. If there’s an error, Python checks for a
matching except block. The finally block always runs, whether an error
occurred or not. Exception handling makes your programs more robust and
user-friendly.
41, What is the difference between break, continue, and pass in Python?
In Python, break, continue, and pass are control flow statements, but each
one serves a different purpose,
* break: It is used to exit a loop completely, even if the loop condition is
still true. Once break is encountered, the loop stops running.
bitpsi/shirsh8¢.macium.convtop-100-pythor-nterview-questions-and.answors-4e403301ASb6 20184‘718/25, 8:26 AM Top 100 Python interview Questions and Answers | by Shirsh Shukla | Medium
for i in range(5):
if i= 3:
break
print(4)
© continue : It skips the current iteration and moves to the next one without
stopping the loop.
for i in range(5):
if iss 3:
continue
print (i)
* pass : It does nothing and is used as a placeholder where code is required
syntactically but no action is needed.
for 4 in range(5):
if i= 3:
pass
print (i)
These are useful for controlling how loops and conditionals behave during
execution,
42. What are Python decorators?
itpss/shirsh8¢.macium.convtop-100-pythor nterview-questions-and.answors-4c409301Sb6 0784res, 0:0 Me “ep 100 Python Itervew Questions and Answers |by hrs Shukla | Mesum
A decorator in Python is a function that takes another function as input and
adds extra functionality to it, without changing its original structure. It is
often used to modify the behavior of a function or method dynamically.
def decorator (func) :
def wrapper():
print("Before function call")
func()
print("after function call")
return wrapper
@decorator
def greet():
print("Hello!")
greet()
Here, @decorator wraps the greet() function and adds extra code before and
after it. Decorators are used often in logging, authentication, timing, and
access control. They help you write cleaner, reusable, and more readable
code.
43. What isa counter in Python?
Counter is a class from the collections module that helps count occurrences
of elements in an iterable. It returns a dictionary-like object where elements
are stored as keys and counts as values.
Example:
-ntps:i/shish3e.medlum.comtop-100-pythor-intrviow-questions-and-answors-4¢4099014806 sire