30 Python Interview Questions
30 Python Interview Questions
Explanation: Python is interpreted, dynamically typed, high-level, and supports multiple paradigms like OOP
Q2 (Easy - Variables): What is the difference between a variable and a constant in Python?
Explanation: Python doesn't have constants by default, but variables are used to store data that can change.
Explanation: int, float, str, list, tuple, dict, set, bool, NoneType are some built-in data types.
s = 'hello'
print(s[::-1])
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
x = 5
if x > 0:
print('Positive')
elif x < 0:
print('Negative')
else:
print('Zero')
Explanation: It checks conditions in order; the first true condition block is executed.
Q7 (Easy - Functions): What is a function in Python and how do you define one?
def greet(name):
print(greet('Alice'))
Explanation: Functions help organize reusable blocks of code using def keyword.
Q8 (Moderate - Loops): What is the difference between a for loop and a while loop?
Explanation: for loops iterate over sequences; while loops run until a condition is false.
print(squares)
print(key, value)
Q11 (Moderate - OOP): What is a class and how do you instantiate it?
class Car:
self.brand = brand
c = Car('Toyota')
print(c.brand)
Explanation: A class defines a blueprint; instantiate using class name followed by parentheses.
class Animal:
d = Dog()
print(d.speak())
Explanation: Inheritance lets one class inherit attributes and methods from another.
try:
x = 1 / 0
except ZeroDivisionError:
Q14 (Moderate - Files): How do you read a file line by line in Python?
with open('file.txt') as f:
for line in f:
print(line)
def decorator(func):
def wrapper():
print('Before')
func()
print('After')
return wrapper
@decorator
def greet():
print('Hello')
greet()
Explanation: Decorators modify the behavior of functions without changing their code.
def gen():
yield 1
y = gen()
print(next(y))
print(squares)
class A: pass
class B: pass
import threading
def print_num():
print('Number')
t = threading.Thread(target=print_num)
t.start()
Explanation: Python uses reference counting and garbage collection for memory management.
Explanation: Includes speed limitations due to GIL, high memory usage, and lack of mobile development.
Explanation: GIL is a mutex that protects access to Python objects, affecting multithreading.
Explanation: Python stores variables as objects in heap memory, with reference counting.