Python Topic
Basic to Intermediate Questions
1. What is the difference between break, continue, and pass?
Answer:
-
break: Exits the entire loop immediately. -
continue: Skips the current iteration and moves to the next one. -
pass: A null operation - does nothing. Used as a placeholder where syntax requires a statement but you don't want any code to execute.
Example:
python
for i in range(5):
if i == 2:
continue # Skip iteration when i is 2
if i == 4:
break # Exit loop when i is 4
print(i)
# Output: 0, 1, 3
def empty_function():
pass # Placeholder for future code
2. How do you swap two variables in Python?
Answer: Python allows swapping without a temporary variable:
python
a = 5
b = 10
# Pythonic way
a, b = b, a
print(a) # 10
print(b) # 5
3. What are lambda functions? When would you use them?
Answer: Lambda functions are small, anonymous functions defined with the lambda keyword. They can have any number of arguments but only one expression.
Syntax: lambda arguments: expression
Use Cases: When you need a simple function for a short period, typically with functions like map(), filter(), or sort().
Example:
python
# Regular function
def square(x):
return x * x
# Lambda equivalent
square = lambda x: x * x
# Using with map()
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16]
4. What is the difference between range() and xrange()?
Answer: In Python 2, range() returns a list, while xrange() returns a generator (memory efficient). In Python 3, xrange() was removed, and range() behaves like Python 2's xrange() - it returns a range object that generates numbers on demand.
5. How do you reverse a list in Python?
Answer: Several ways:
python
my_list = [1, 2, 3, 4]
# Method 1: Using reverse() method (modifies original)
my_list.reverse()
print(my_list) # [4, 3, 2, 1]
# Method 2: Using slicing (creates new list)
reversed_list = my_list[::-1]
print(reversed_list) # [4, 3, 2, 1]
# Method 3: Using reversed() function
reversed_list = list(reversed(my_list))
print(reversed_list) # [4, 3, 2, 1]
6. What are docstrings in Python?
Answer: Docstrings are string literals that appear right after the definition of a function, method, class, or module. They are used to document code and can be accessed using help() or the __doc__ attribute.
Example:
python
def add_numbers(a, b):
"""
This function adds two numbers and returns the result.
Parameters:
a (int/float): First number
b (int/float): Second number
Returns:
int/float: Sum of a and b
"""
return a + b
print(help(add_numbers))
print(add_numbers.__doc__)
7. How do you handle file operations in Python?
Answer: Using the open() function with different modes:
python
# Writing to a file
with open('file.txt', 'w') as f:
f.write("Hello, World!")
# Reading from a file
with open('file.txt', 'r') as f:
content = f.read()
print(content)
# Appending to a file
with open('file.txt', 'a') as f:
f.write("\nAppended text")
8. What is the difference between / and // operators?
Answer:
-
/: Regular division - returns a float result -
//: Floor division - returns the integer part of the quotient (rounds down)
Example:
python
print(7 / 2) # 3.5
print(7 // 2) # 3
print(-7 // 2) # -4 (rounds towards negative infinity)
9. How do you remove duplicates from a list?
Answer:
python
my_list = [1, 2, 2, 3, 4, 4, 5]
# Method 1: Convert to set and back to list
unique_list = list(set(my_list))
print(unique_list) # [1, 2, 3, 4, 5]
# Method 2: Using dict.fromkeys() (preserves order in Python 3.7+)
unique_list = list(dict.fromkeys(my_list))
print(unique_list) # [1, 2, 3, 4, 5]
# Method 3: Using loop (preserves order)
unique_list = []
for item in my_list:
if item not in unique_list:
unique_list.append(item)
10. What is the purpose of __name__ == "__main__"?
Answer: This construct allows you to execute code only when the script is run directly, not when it's imported as a module.
Example:
python
# my_script.py
def my_function():
print("This is a function")
if __name__ == "__main__":
print("Script is running directly")
my_function()
# When run directly: Both print statements execute
# When imported: Only the function definition is loaded
Object-Oriented Programming Questions
11. Explain inheritance in Python with an example.
Answer: Inheritance allows a class to inherit attributes and methods from another class.
Example:
python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal): # Dog inherits from Animal
def speak(self):
return "Woof!"
class Cat(Animal): # Cat inherits from Animal
def speak(self):
return "Meow!"
dog = Dog("Buddy")
print(dog.name) # Buddy
print(dog.speak()) # Woof!
12. What is method overriding?
Answer: Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its parent class.
Example:
python
class Parent:
def show(self):
print("Parent's method")
class Child(Parent):
def show(self): # Overriding parent's method
print("Child's method")
obj = Child()
obj.show() # Output: "Child's method"
13. What are getters and setters in Python? How do you implement them?
Answer: Getters and setters are used to control access to class attributes. In Python, we use properties with the @property decorator.
Example:
python
class Person:
def __init__(self, name):
self._name = name # Private variable convention
@property
def name(self): # Getter
return self._name
@name.setter
def name(self, value): # Setter
if isinstance(value, str):
self._name = value
else:
raise ValueError("Name must be a string")
person = Person("Alice")
print(person.name) # Alice (using getter)
person.name = "Bob" # Using setter
print(person.name) # Bob
14. What is the difference between instance variables and class variables?
Answer:
-
Instance variables: Belong to each instance/object. Defined using
self.variable_name -
Class variables: Shared by all instances. Defined within the class but outside any methods
Example:
python
class Car:
wheels = 4 # Class variable
def __init__(self, brand):
self.brand = brand # Instance variable
car1 = Car("Toyota")
car2 = Car("Honda")
print(car1.wheels) # 4
print(car2.wheels) # 4
Car.wheels = 6 # Affects all instances
print(car1.wheels) # 6
Intermediate to Advanced Questions
15. What is the difference between @staticmethod and @classmethod?
Answer:
-
@staticmethod: Doesn't receive any implicit first argument. Can't access or modify class state. -
@classmethod: Receives the class (cls) as first argument. Can access and modify class state.
Example:
python
class MyClass:
class_var = 10
def __init__(self, value):
self.value = value
@classmethod
def class_method(cls):
return f"Class variable: {cls.class_var}"
@staticmethod
def static_method():
return "This is a static method"
print(MyClass.class_method()) # Class variable: 10
print(MyClass.static_method()) # This is a static method
16. What are context managers? How do you create one?
Answer: Context managers manage resources and ensure proper cleanup. You can create one using:
-
A class with
__enter__and__exit__methods -
The
contextlibmodule with@contextmanagerdecorator
Example using class:
python
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
# Usage
with FileManager('test.txt', 'w') as f:
f.write('Hello')
17. How does Python's garbage collection work?
Answer: Python uses:
-
Reference counting: Objects are deleted when their reference count drops to zero
-
Generational garbage collection: For handling circular references, it uses three generations and collects older objects less frequently
Example:
python
import gc
# Check GC thresholds
print(gc.get_threshold()) # (700, 10, 10)
# Manually trigger collection
gc.collect()
18. What are metaclasses in Python?
Answer: Metaclasses are the "classes of classes" that define how classes behave. The default metaclass is type.
Example:
python
# Creating a class using type metaclass
MyClass = type('MyClass', (), {'attribute': 100})
obj = MyClass()
print(obj.attribute) # 100
# Custom metaclass
class Meta(type):
def __new__(cls, name, bases, dct):
dct['custom_attr'] = 50
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
print(MyClass.custom_attr) # 50
19. How do you handle JSON in Python?
Answer: Using the json module:
python
import json
# Python object to JSON string
data = {'name': 'John', 'age': 30, 'cities': ['NYC', 'London']}
json_string = json.dumps(data)
print(json_string)
# JSON string to Python object
python_obj = json.loads(json_string)
print(python_obj['name']) # John
# Working with files
with open('data.json', 'w') as f:
json.dump(data, f)
with open('data.json', 'r') as f:
loaded_data = json.load(f)
20. What is the difference between __str__ and __repr__?
Answer:
-
__str__: Meant for end-users - informal, readable representation -
__repr__: Meant for developers - official, unambiguous representation (should ideally allow recreating the object)
Example:
python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
p = Point(3, 4)
print(str(p)) # Point(3, 4) - user friendly
print(repr(p)) # Point(x=3, y=4) - developer friendly
Bonus: Problem-Solving Questions
21. How would you find the most frequent element in a list?
Answer:
python
from collections import Counter
def most_frequent(lst):
counter = Counter(lst)
return counter.most_common(1)[0][0]
# Example
numbers = [1, 3, 2, 1, 4, 1, 3, 1]
print(most_frequent(numbers)) # 1
22. How do you check if a string is a palindrome?
Answer:
python
def is_palindrome(s):
s = s.lower().replace(' ', '') # Case insensitive, ignore spaces
return s == s[::-1]
print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False
print(is_palindrome("A man a plan a canal Panama")) # True
These questions cover a wide range of Python concepts that are commonly asked in fresher interviews. Practice explaining the concepts clearly and writing clean, efficient code!
Comments (0)
No comments yet. Be the first to comment!