🚀 Fast Revision Before Interviews
This page helps you quickly revise essential Python concepts with key bullet points, syntax examples, and interview tips. Perfect for last-minute preparation and concept reinforcement!
📚 Concept Summary
Variables & Data Types
Key Points:
- Python is dynamically typed - no need to declare variable types
- Main types: int, float, str, bool, list, tuple, dict, set
- Variables are case-sensitive
- Use type() to check data type
# Variable assignment
name = "Alice" # str
age = 25 # int
height = 5.6 # float
is_student = True # bool
# Type checking
print(type(name)) # <class 'str'>
💡 Interview Tip: Remember that Python uses duck typing - "If it walks like a duck and quacks like a duck, it's a duck."
Strings
Key Points:
- Immutable sequences of characters
- Use single, double, or triple quotes
- Support slicing and indexing
- Many built-in methods available
# String operations
text = "Hello World"
print(text[0]) # 'H'
print(text[1:5]) # 'ello'
print(text.upper()) # 'HELLO WORLD'
print(text.split()) # ['Hello', 'World']
# f-strings (Python 3.6+)
name = "Alice"
print(f"Hello {name}!") # Hello Alice!
💡 Interview Tip: Know string methods like split(), join(), strip(), replace(), and understand string slicing syntax.
Lists
Key Points:
- Mutable, ordered collections
- Can contain different data types
- Support indexing, slicing, and iteration
- Dynamic size - can grow and shrink
# List operations
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Add to end
fruits.insert(1, "mango") # Insert at index
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove and return last
# List comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
💡 Interview Tip: Master list comprehensions and know the difference between append(), extend(), and insert().
Dictionaries
Key Points:
- Mutable, unordered key-value pairs
- Keys must be immutable (strings, numbers, tuples)
- Fast lookup, insertion, and deletion
- No duplicate keys allowed
# Dictionary operations
person = {"name": "Alice", "age": 25, "city": "NY"}
person["email"] = "alice@email.com" # Add new key-value
age = person.get("age", 0) # Safe access with default
# Dictionary methods
keys = person.keys() # dict_keys(['name', 'age', 'city', 'email'])
values = person.values() # dict_values(['Alice', 25, 'NY', 'alice@email.com'])
items = person.items() # dict_items([('name', 'Alice'), ...])
💡 Interview Tip: Use get() method to avoid KeyError. Know dict comprehensions and the difference between keys(), values(), and items().
Loops & Control Flow
Key Points:
- for loops for iteration, while loops for conditions
- Use break to exit loop, continue to skip iteration
- else clause can be used with loops
- enumerate() and zip() are useful for loops
# For loop with enumerate
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# While loop
count = 0
while count < 5:
print(count)
count += 1
# Loop with else
for i in range(5):
if i == 10:
break
else:
print("Loop completed normally") # This will execute
💡 Interview Tip: Remember that else clause in loops executes only if loop completes normally (no break).
Functions
Key Points:
- Reusable blocks of code with def keyword
- Support default parameters and keyword arguments
- Can return multiple values as tuple
- *args for variable positional, **kwargs for variable keyword arguments
# Function with default parameters
def greet(name, message="Hello"):
return f"{message}, {name}!"
# Function with *args and **kwargs
def flexible_func(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)
flexible_func(1, 2, 3, name="Alice", age=25)
# Lambda function
square = lambda x: x**2
print(square(5)) # 25
💡 Interview Tip: Understand scope (local vs global), know when to use lambda functions, and remember that functions are first-class objects.
Object-Oriented Programming (OOP)
Key Points:
- Classes define blueprints, objects are instances
- __init__ is constructor, self refers to instance
- Inheritance with super() for parent class access
- Encapsulation with private attributes (_attribute)
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
return "Some generic sound"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Canine")
self.breed = breed
def make_sound(self):
return "Woof!"
# Usage
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.make_sound()) # Woof!
💡 Interview Tip: Know the four OOP pillars: Encapsulation, Inheritance, Polymorphism, and Abstraction.
Exception Handling
Key Points:
- Use try-except blocks to handle errors gracefully
- finally block always executes
- else block executes if no exception occurs
- Can raise custom exceptions with raise keyword
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No errors occurred")
finally:
print("This always executes")
# Raising custom exception
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
💡 Interview Tip: Always catch specific exceptions rather than using bare except. Know common exception types.
File Operations
Key Points:
- Use open() with context manager (with statement)
- Different modes: 'r' (read), 'w' (write), 'a' (append)
- Always close files or use with statement
- Handle file exceptions appropriately
# Reading a file
with open('file.txt', 'r') as file:
content = file.read()
lines = file.readlines()
# Writing to a file
with open('output.txt', 'w') as file:
file.write("Hello World\n")
file.writelines(["Line 1\n", "Line 2\n"])
# File existence check
import os
if os.path.exists('file.txt'):
print("File exists")
💡 Interview Tip: Always use context managers (with statement) for file operations to ensure proper cleanup.
🎯 Interview Focus Questions
- What is the difference between list and tuple?
- Explain mutable vs immutable objects in Python
- What are list comprehensions and when to use them?
- Difference between == and is operators?
- What is the GIL (Global Interpreter Lock)?
- Explain *args and **kwargs with examples
- What are decorators and how do they work?
- Difference between deep copy and shallow copy?
- What are generators and yield keyword?
- Explain Python's memory management
- What is the difference between @staticmethod and @classmethod?
- How does exception handling work in Python?
- What are context managers and the with statement?
- Explain the concept of closures in Python
- What is the difference between range() and xrange()?
⚡ Quick Syntax Cheat Sheet
# LOOPS for i in range(5): # 0 to 4 print(i) for item in [1,2,3]: # Iterate over list print(item) while condition: # While loop # code here break # Exit loop continue # Skip iteration # CONDITIONALS if x > 0: print("Positive") elif x == 0: print("Zero") else: print("Negative") # FUNCTIONS def function_name(param1, param2=default): """Docstring here""" return result # LAMBDA lambda x: x**2 # Anonymous function # CLASSES class MyClass: def __init__(self, value): self.value = value def method(self): return self.value # LIST COMPREHENSION [x**2 for x in range(10) if x%2==0] # Even squares # DICTIONARY COMPREHENSION {k: v for k, v in items if condition} # EXCEPTION HANDLING try: # risky code pass except SpecificError: # handle error pass finally: # cleanup code pass # CONTEXT MANAGER with open('file.txt', 'r') as f: content = f.read() # GENERATORS def generator(): yield value # DECORATORS @decorator def function(): pass
🚀 Practice daily coding and revise these concepts regularly to crack interviews! 🚀
Success comes from consistent practice and understanding, not just memorization!
Success comes from consistent practice and understanding, not just memorization!