Basic Python Questions
What is Python?
Python is an interpreted, high-level, dynamically typed, and garbage-collected programming language.What are Python’s key features?
- Easy to learn and use
- Interpreted and dynamically typed
- Object-oriented
- Extensive standard library
How do you write "Hello, World!" in Python?
print("Hello, World!")How do you check the Python version?
import sys print(sys.version)How do you take user input in Python?
name = input("Enter your name: ") print("Hello, " + name)How do you comment in Python?
- Single-line comment:
# This is a comment - Multi-line comment:
"""This is a multi-line comment"""
- Single-line comment:
What are Python’s data types?
- Numeric (int, float, complex)
- Sequence (list, tuple, range)
- Text (str)
- Set (set, frozenset)
- Mapping (dict)
- Boolean (bool)
What is the difference between
isand==in Python?==checks for value equality.ischecks for reference (memory) equality.
How do you declare a variable in Python?
x = 10 y = "Python"What is dynamic typing?
Python does not require explicit variable declarations; the type is assigned dynamically.
Control Flow & Loops
What are conditional statements in Python?
if x > 0: print("Positive") elif x < 0: print("Negative") else: print("Zero")How do you write a
forloop?for i in range(5): print(i)How do you write a
whileloop?x = 0 while x < 5: print(x) x += 1What is the difference between
breakandcontinue?breakexits the loop.continueskips the current iteration.
How do you use a
passstatement?for i in range(5): pass # Placeholder for future code
Functions & Scope
How do you define a function in Python?
def greet(): print("Hello!")What are function arguments in Python?
def add(a, b): return a + bWhat is the difference between positional and keyword arguments?
- Positional:
add(2, 3) - Keyword:
add(a=2, b=3)
- Positional:
What is a default argument in Python?
def greet(name="Guest"): print("Hello, " + name)What is variable scope in Python?
- Local: Defined inside a function.
- Global: Defined outside any function.
Data Structures
What is a list?
my_list = [1, 2, 3, 4, 5]How do you access list elements?
print(my_list[0]) # First elementHow do you slice a list?
print(my_list[1:4]) # [2, 3, 4]What is a tuple?
my_tuple = (1, 2, 3)How do you create a dictionary?
my_dict = {"name": "Alice", "age": 25}
OOP in Python
How do you define a class in Python?
class Person: def __init__(self, name): self.name = nameWhat is an object?
p = Person("Alice")What is inheritance in Python?
class Employee(Person): passWhat is polymorphism?
Different classes implementing the same method.What is encapsulation?
Hiding the internal state of an object.
File Handling
How do you open a file in Python?
f = open("file.txt", "r")How do you read a file?
content = f.read()How do you write to a file?
with open("file.txt", "w") as f: f.write("Hello, World!")How do you close a file?
f.close()
Error Handling
How do you handle exceptions in Python?
try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero")What is
finallyin exception handling?try: x = 1 / 0 except: print("Error") finally: print("This always runs")How do you raise an exception?
raise ValueError("Invalid value")
Advanced Python
What are lambda functions?
add = lambda x, y: x + yWhat is a list comprehension?
squares = [x**2 for x in range(10)]What is a generator?
def my_gen(): yield 1 yield 2What is multithreading?
Running multiple threads in parallel.How do you install an external package?
pip install requestsWhat is a virtual environment in Python?
It isolates dependencies for projects.What is the
mapfunction?list(map(str, [1, 2, 3]))What is
filterin Python?list(filter(lambda x: x % 2 == 0, range(10)))What is
reduce?from functools import reduce reduce(lambda x, y: x + y, [1, 2, 3, 4])
Intermediate Python Concepts
What are Python’s built-in data types?
int,float,complex,str,list,tuple,dict,set,bool,NoneType.
What is the difference between a list and a tuple?
- Lists are mutable, whereas tuples are immutable.
How do you reverse a list in Python?
my_list.reverse() # or reversed_list = my_list[::-1]How do you sort a list in Python?
my_list.sort() # Sorts in place sorted_list = sorted(my_list) # Returns a new sorted listHow do you merge two dictionaries?
dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} merged_dict = {**dict1, **dict2}How do you remove duplicates from a list?
my_list = list(set(my_list))What is the difference between
remove()andpop()in lists?remove(value): Removes the first occurrence of the specified value.pop(index): Removes the element at the given index.
What is the
zip()function used for?a = [1, 2, 3] b = ['x', 'y', 'z'] zipped = list(zip(a, b)) # [(1, 'x'), (2, 'y'), (3, 'z')]How do you check if a key exists in a dictionary?
if "key" in my_dict: print("Exists")What is the difference between
delandclear()in dictionaries?del my_dict['key']: Removes a specific key-value pair.my_dict.clear(): Removes all key-value pairs.
How do you iterate over a dictionary?
for key, value in my_dict.items(): print(key, value)
String Manipulation
How do you split a string?
text = "apple,banana,cherry" fruits = text.split(",") # ['apple', 'banana', 'cherry']How do you join a list of strings?
joined = ", ".join(fruits) # "apple, banana, cherry"How do you check if a string contains a substring?
if "apple" in text: print("Found")How do you replace a substring in Python?
text = text.replace("apple", "orange")What is string formatting in Python?
name = "Alice" age = 25 print(f"My name is {name} and I am {age} years old.")
Advanced Python Concepts
What are Python decorators?
- Decorators are functions that modify the behavior of other functions.
def decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper @decorator def say_hello(): print("Hello!") say_hello()What is the difference between
deepcopy()andcopy()?copy.copy(): Creates a shallow copy (nested objects are referenced).copy.deepcopy(): Creates a deep copy (nested objects are also copied).
What is the purpose of
__init__.py?- It marks a directory as a Python package.
What is monkey patching in Python?
- Dynamically modifying a class or module at runtime.
What is the purpose of the
super()function?- It calls the parent class’s method inside a subclass.
How do you define an abstract class?
from abc import ABC, abstractmethod class AbstractClass(ABC): @abstractmethod def abstract_method(self): passWhat is method overloading in Python?
- Python does not support method overloading directly; instead, default arguments can be used.
What is method overriding?
- A subclass provides a new implementation of a method inherited from its parent class.
What are metaclasses in Python?
- Metaclasses define how classes behave.
Python Libraries & Modules
How do you import a module in Python?
import mathHow do you list all installed modules?
help("modules")What is
sys.argvin Python?- It contains command-line arguments passed to a script.
How do you measure execution time in Python?
import time start = time.time() # Code execution end = time.time() print(f"Time taken: {end - start}")What is
osmodule used for?- To interact with the operating system.
How do you get the current working directory?
import os print(os.getcwd())How do you rename a file in Python?
os.rename("old.txt", "new.txt")What is the
randommodule used for?import random print(random.randint(1, 10))How do you generate a random float number?
print(random.uniform(1.0, 10.0))What is NumPy used for?
- It is used for numerical computations.
How do you create a NumPy array?
import numpy as np arr = np.array([1, 2, 3])What is Pandas used for?
- Data analysis and manipulation.
How do you read a CSV file using Pandas?
import pandas as pd df = pd.read_csv("file.csv")
Python Best Practices
What is PEP 8?
- Python Enhancement Proposal 8 (PEP 8) is a style guide for writing readable code.
What is the Zen of Python?
import thisWhy should you use
withwhen opening files?- It automatically closes the file.
What is the purpose of
__name__ == "__main__"?- It ensures the script runs only when executed directly.
What is duck typing in Python?
- The type of an object is determined by its behavior.
What is the
walrusoperator (:=)?if (n := len(my_list)) > 5: print(f"List is too long: {n}")What is the difference between
isinstance()andtype()?isinstance()considers inheritance,type()does not.
What is a frozen set?
my_set = frozenset([1, 2, 3])What are Python f-strings?
name = "Alice" print(f"Hello, {name}")How do you handle multiple exceptions?
try: pass except (TypeError, ValueError) as e: print(e)What is the
collectionsmodule used for?- It provides specialized data structures like
Counter,deque, etc.
- It provides specialized data structures like
What is a namedtuple?
pythonfrom collections import namedtuple Point = namedtuple("Point", "x y") p = Point(1, 2)
Would you like more questions on a specific topic? 🚀