Python_Notes_with_Interview_Questions (1)
Python_Notes_with_Interview_Questions (1)
1. Introduction to Python
Python is a high-level, interpreted programming language known for its readability and
versatility.
Code Example:
print("Hello, World!")
Interview Question:
What are the key features of Python?
Answer:
Python is interpreted, dynamically typed, garbage-collected, supports multiple paradigms,
and has a large standard library.
2. Python Basics
Covers variables, data types, operators, input/output, and basic control structures.
Code Example:
x = 10
y = 20
print("Sum:", x + y)
Interview Question:
What is the difference between list and tuple in Python?
Answer:
Lists are mutable whereas tuples are immutable.
def greet(name):
return f"Hello, {name}"
print(greet("Alice"))
Interview Question:
What is the difference between a module and a package in Python?
Answer:
A module is a single Python file, while a package is a collection of modules in directories
that include a __init__.py file.
4. Data Structures
Python provides built-in data structures such as lists, tuples, sets, and dictionaries. These
are highly optimized and easy to use.
Code Example:
my_list = [1, 2, 3, 4]
my_tuple = (1, 2, 3, 4)
my_set = {1, 2, 3, 4}
my_dict = {'a': 1, 'b': 2}
Interview Question:
How is a set different from a list in Python?
Answer:
A set is an unordered collection of unique elements, whereas a list is an ordered collection
that can contain duplicates.
Code Example:
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f'Hello, {self.name}'
p = Person('John')
print(p.greet())
Interview Question:
What is inheritance in Python?
Answer:
Inheritance allows one class to inherit the attributes and methods of another class,
promoting code reusability.
6. Exception Handling
Python uses try-except blocks to handle exceptions gracefully and prevent program crashes.
Code Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
Interview Question:
What is the purpose of finally block in exception handling?
Answer:
The finally block is executed regardless of whether an exception occurred, and is typically
used for cleanup actions.
7. File Handling
Python provides functions to read from and write to files. The `with` statement is used to
handle file operations safely.
Code Example:
Interview Question:
Why is the 'with' statement used when working with files?
Answer:
The 'with' statement ensures the file is properly closed after its suite finishes, even if an
exception is raised.
Code Example:
Interview Question:
What is a lambda function in Python?
Answer:
A lambda function is an anonymous function defined with the lambda keyword, often used
for short, throwaway functions.