Python Terminology Cheat Sheet – Essential concepts for interview success in a sleek, tech-themed design.
Preparing for a Python interview can feel stressful, especially when you run into tricky technical terms. But don’t worry—I’ve got you! Here is the Python Terminology Cheat Sheet.
This Python terminology cheat sheet covers the most important terms you’ll need. You’ll go through data types, loops, functions, OOP, exception handling, and more. Whether you’re just starting or brushing up, this guide will make things simple.
Knowing these terms will help you explain your answers better and feel more confident. Let’s get started!
Think of variables as boxes where you store data. In Python, you don’t have to say what type of data you’re storing—Python figures it out for you.
Example:
x = 10 # A whole number (integer)
name = "Alex" # A piece of text (string)
pi = 3.14 # A decimal number (float)
So if you write x = 10, Python just knows it’s a number. No need to say int x = 10; like in other languages.
Python has different types of data, and each one is used for a specific purpose.
int) → Whole numbersage = 25
float) → Numbers with decimalsprice = 9.99
str) → Text inside quotesname = "Python"
list) → A collection of items that can changefruits = ["apple", "banana", "cherry"]
tuple) → Like lists, but can’t be changedcolors = ("red", "blue", "green")
set) → A collection of unique items, no duplicatesunique_numbers = {1, 2, 3, 3} # Python automatically removes duplicate 3
dict) → Key-value pairs, like a mini databaseperson = {"name": "Alice", "age": 30}
Some data types in Python can be changed after they’re created, and some can’t.
list, set, dictfruits = ["apple", "banana"]
fruits.append("cherry") # This works!
str, tuple, int, floatname = "Python"
name[0] = "J" # ❌ This gives an error! Strings can’t be changed like this
Operators are special symbols that let you perform operations on variables and values. Python has different types of operators, each with its own job.
These are used for basic math operations.
+ (Addition) → Adds two numbers.x = 5 + 3 # x is 8
- (Subtraction) → Subtracts one number from another.y = 10 - 4 # y is 6
* (Multiplication) → Multiplies two numbers.* (Multiplication) → Multiplies two numbers/ (Division) → Divides one number by another (gives a decimal).a = 10 / 2 # a is 5.0
% (Modulus) → Gives the remainder of a division.b = 10 % 3 # b is 1 (since 10 ÷ 3 = 3 remainder 1)
** (Exponent) → Raises a number to a power.c = 2 ** 3 # c is 8 (2³)
Quick Tip:
Use % (modulus) to check if a number is even or odd:
num = 7
if num % 2 == 0:
print("Even")
else:
print("Odd")
These compare two values and return True or False.
== (Equal to) → Checks if two values are the same.5 == 5 # True
!= (Not equal to) → Checks if two values are different.5 != 3 # True
> (Greater than) → Checks if the first value is bigger.10 > 5 # True
< (Less than) → Checks if the first value is smaller.3 < 7 # True
>= (Greater than or equal to) → Checks if the first value is bigger or equal.5 >= 5 # True
<= (Less than or equal to) → Checks if the first value is smaller or equal.4 <= 6 # True
Quick Tip:
Use == for comparison, not = (which is for assignment).
x = 10 # Assigns 10 to x
if x == 10: # Compares x with 10
print("x is 10")
These are used when you need to check multiple conditions at once.
and → Returns True if both conditions are true.(5 > 2) and (10 > 3) # True
or → Returns True if at least one condition is true.(5 > 2) or (10 < 3) # True
not → Reverses the result (True becomes False, and vice versa).not (5 > 2) # False
Quick Tip:
Use and when both conditions must be true, and or when at least one must be true.
age = 20
if age > 18 and age < 30:
print("You're in your 20s!")
These work on numbers at the binary (bit) level. You won’t use them much unless you’re working with low-level programming or optimization.
& (AND) → Compares bits and keeps only the 1s that match.5 & 3 # 5 (101) & 3 (011) = 1 (001)
| (OR) → Compares bits and keeps any 1s it finds.5 | 3 # 5 (101) | 3 (011) = 7 (111)
^ (XOR) → Keeps 1s where the bits are different.5 ^ 3 # 5 (101) ^ 3 (011) = 6 (110)
<< (Left Shift) → Moves bits to the left (multiplies by 2).5 << 1 # 5 (101) becomes 10 (1010)
>> (Right Shift) → Moves bits to the right (divides by 2).5 >> 1 # 5 (101) becomes 2 (10)
Quick Tip:
Use left shift << to multiply by powers of 2, and right shift >> to divide by powers of 2.
x = 4
print(x << 1) # 8 (4 * 2)
print(x >> 1) # 2 (4 / 2)
Control flow is how Python decides what to run next in your code. It’s like giving your program a set of rules to follow.
The if statement helps your code make choices. It runs a block of code only if a certain condition is true.
age = 18
if age >= 18:
print("You're an adult!")
else:
print("You're a minor!")
Quick Tip:
Use elif (short for “else if”) when checking multiple conditions.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C")
Loops let you run the same code multiple times without repeating yourself.
A for loop runs through a list, string, or range of numbers one item at a time.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Quick Tip:
Use range(n) to loop through numbers from 0 to n-1.
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
A while loop keeps running as long as a condition is true.
count = 1
while count <= 5:
print(count)
count += 1 # Increase count to avoid an infinite loop
Be Careful!
If the condition never becomes false, the loop won’t stop (infinite loop!).
while True:
print("This will run forever!") # Don’t do this!
These help you control how a loop behaves.
Use break to stop the loop early when a condition is met.
for num in range(10):
if num == 5:
break # Stops the loop when num is 5
print(num)
Use continue to skip the current loop iteration and move to the next one.
for num in range(5):
if num == 2:
continue # Skips 2
print(num)
pass is used when you need a placeholder but don’t want your code to break.
for num in range(5):
if num == 2:
pass # Does nothing
print(num)
Quick Tip:
Use pass when writing code that you’ll fill in later.
Functions let you group code into a single block so you can reuse it without repeating yourself. This makes your code cleaner and easier to manage.
You create a function using the def keyword.
def greet():
print("Hello, welcome!")
To use the function, just call it by its name:
greet() # Output: Hello, welcome!
Quick Tip: Always give your functions clear names so others can understand what they do.
You can pass values (parameters) to a function.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
Quick Tip: Functions can have multiple parameters too.
def add(a, b):
return a + b
print(add(5, 3)) # Output: 8
You can set default values for parameters.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Bob") # Output: Hello, Bob!
Quick Tip: Default parameters are useful when you don’t always need to provide a value.
Lambda functions are tiny functions that don’t need a def keyword.
square = lambda x: x * x
print(square(4)) # Output: 16
When to Use Lambda?
map(), filter(), or sorted()Example:
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
Python is an object-oriented programming (OOP) language. This means you can create blueprints (classes) and make real-world objects from them.
A class is like a template for creating objects. It defines what an object should have (attributes) and what it can do (methods).
class Car:
def __init__(self, brand):
self.brand = brand # Attribute (stores car brand)
Think of a class like a blueprint for a house. The blueprint tells you what a house should have (rooms, doors, windows), but it’s not a house itself.
An object is an actual thing created from a class.
my_car = Car("Toyota")
print(my_car.brand) # Output: Toyota
If the class is a blueprint, an object is the house you build from it!
__init__ Method (Constructor)__init__ is a special method that runs automatically when you create an object. It’s used to set up attributes.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Alice", 25)
print(p1.name) # Output: Alice
print(p1.age) # Output: 25
self refers to the current object and lets you store values inside it.
A class can have methods (functions inside a class) that perform actions.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says Woof!")
d1 = Dog("Buddy")
d1.bark() # Output: Buddy says Woof!
Methods let objects do things! Here, every Dog object can bark().
You can create many objects from the same class.
car1 = Car("Honda")
car2 = Car("Ford")
print(car1.brand) # Output: Honda
print(car2.brand) # Output: Ford
Each object has its own data! Changing car1.brand won’t affect car2.brand.
Encapsulation means restricting access to certain data in a class. This prevents accidental modification.
self.name).__salary). These can’t be accessed directly from outside the class.class Employee:
def __init__(self, name, salary):
self.name = name # Public variable
self.__salary = salary # Private variable
def get_salary(self): # Public method to access private data
return self.__salary
emp = Employee("John", 50000)
print(emp.name) # Output: John
# print(emp.__salary) # ❌ This will give an error
print(emp.get_salary()) # ✅ Correct way to access private data (Output: 50000)
Why use encapsulation? It protects sensitive data and only allows access through controlled methods.
Inheritance allows a class (child class) to reuse the code of another class (parent class).
class Animal:
def speak(self):
print("This animal makes a sound")
class Dog(Animal): # Dog inherits from Animal
def speak(self):
print("Woof! Woof!")
dog = Dog()
dog.speak() # Output: Woof! Woof!
Why use inheritance? It reduces code repetition and makes programs more organized.
Polymorphism means using the same method name in different ways.
Example: Different classes have a speak() method, but they behave differently.
class Cat:
def speak(self):
print("Meow!")
class Bird:
def speak(self):
print("Chirp!")
# Using the same method name across different classes
animals = [Cat(), Bird()]
for animal in animals:
animal.speak()
# Output:
# Meow!
# Chirp!
Why use polymorphism? It allows flexibility—you can write general code that works with different object types.
Python has special methods called dunder (double underscore) methods. These start and end with __.
__init__ (Constructor Method – Runs When Object is Created)This automatically initializes attributes when you create an object.
class Car:
def __init__(self, brand):
self.brand = brand
my_car = Car("Tesla")
print(my_car.brand) # Output: Tesla
Why use __init__? It saves you from manually setting attributes every time you create an object.
__str__ (How an Object is Printed as a String)By default, printing an object gives something unreadable like <__main__.Car object at 0x0000023B>.
With __str__, you control how an object is displayed.
class Car:
def __init__(self, brand):
self.brand = brand
def __str__(self):
return f"Car Brand: {self.brand}"
my_car = Car("BMW")
print(my_car) # Output: Car Brand: BMW
Why use __str__? It makes debugging easier by showing useful info instead of memory addresses.
Encapsulation, Inheritance, and Polymorphism help structure code in a way that’s secure, reusable, and flexible. And dunder methods make objects more intuitive to work with.
For your interview: Be ready to explain these concepts and write simple examples!
List comprehensions let you create lists in a single line instead of using loops. They’re faster and cleaner.
Example: Create a list of squares from 0 to 4.
squares = [x * x for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Tip: You can also use conditions inside list comprehensions!
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]
Generators produce values one at a time instead of storing them all in memory. This is useful for large datasets.
Example: A generator that produces squares on demand.
def square_generator(n):
for x in range(n):
yield x * x # 'yield' returns one value at a time
gen = square_generator(5)
print(next(gen)) # Output: 0
print(next(gen)) # Output: 1
Tip: Generators are memory-efficient because they don’t store all values at once. Use them when working with large files or infinite sequences.
A decorator is a function that wraps another function to modify its behavior.
Example: A decorator that logs function calls.
def logger(func):
def wrapper():
print(f"Calling {func.__name__}()")
func()
return wrapper
@logger
def say_hello():
print("Hello!")
say_hello()
# Output:
# Calling say_hello()
# Hello!
Tip: Use decorators to add logging, authentication, or timing to functions without modifying their original code.
A closure is a function that remembers variables from its enclosing scope even after the scope has finished executing.
Example:
def outer_function(msg):
def inner_function():
print(msg) # 'msg' is remembered even after outer_function finishes
return inner_function
greet = outer_function("Hi there!")
greet() # Output: Hi there!
Tip: Closures are useful for data hiding and creating function factories.
An iterable is any object you can loop through (lists, tuples, dictionaries, etc.).
numbers = [1, 2, 3]
for num in numbers:
print(num) # Output: 1 2 3
An iterator is an object that remembers where it is in a sequence. It works with the next() function.
Example: Manually iterating through a list.
numbers = iter([1, 2, 3])
print(next(numbers)) # Output: 1
print(next(numbers)) # Output: 2
Tip: Use iter() and next() when you don’t want to load everything in memory at once.
try-except-finally)Exceptions happen when your code runs into an error (like dividing by zero). Instead of crashing the program, you can handle errors gracefully.
Example: Handling division by zero.
try:
x = 1 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
finally:
print("This runs no matter what.")
Tip: The finally block always runs, whether there’s an error or not. Use it to close files, release resources, or clean up memory.
Mastering list comprehensions, generators, decorators, iterators, and exception handling will make you write cleaner, more efficient Python code. These are common topics in coding interviews, so practice them well!
Python automatically cleans up unused objects to free memory. This process is called garbage collection.
Example:
import sys
x = [1, 2, 3]
y = x # Now, two variables point to the same list
print(sys.getrefcount(x)) # Output: 3 (x, y, and an internal reference)
del x # Remove one reference
print(sys.getrefcount(y)) # Output: 2
Tip: Circular references (objects pointing to each other) can prevent garbage collection. Use gc.collect() to force cleanup when needed.
Python uses something called the Global Interpreter Lock (GIL). This means only one thread can execute Python code at a time, even on multi-core processors.
multiprocessing) is better than threads.Example: Using threading vs. multiprocessing:
import threading
import multiprocessing
def task():
print("Running...")
# Threading (affected by GIL)
t = threading.Thread(target=task)
t.start()
# Multiprocessing (bypasses GIL)
p = multiprocessing.Process(target=task)
p.start()
Tip: If you need true parallel processing, use the multiprocessing module instead of threading.
A shallow copy creates a new object, but it still points to the original data. Changes to nested objects will reflect in both copies.
Example:
import copy
original = [[1, 2, 3], [4, 5, 6]]
shallow_copy = copy.copy(original)
shallow_copy[0][0] = 99
print(original) # Output: [[99, 2, 3], [4, 5, 6]]
Tip: Use shallow copies when you don’t need to fully separate objects.
A deep copy makes a completely independent copy. Changes in the new object won’t affect the original.
Example:
deep_copy = copy.deepcopy(original)
deep_copy[0][0] = 42
print(original) # Output: [[99, 2, 3], [4, 5, 6]] (Unchanged)
Tip: Use deepcopy() when working with nested structures and you want a true copy.
multiprocessing for CPU-heavy tasks.These are common interview topics, so practice them well!
A module is just a Python file that contains functions, classes, or variables you can reuse in other programs. Instead of writing everything from scratch, you can import code from other files or external libraries.
You can import a module using the import statement:
import math # Imports the entire math module
print(math.sqrt(25)) # Output: 5.0
Tip: Use import module_name as alias to make names shorter:
import numpy as np
arr = np.array([1, 2, 3])
print(arr) # Output: [1 2 3]
Instead of importing the whole module, you can import only what you need:
from math import sqrt, pi
print(sqrt(36)) # Output: 6.0
print(pi) # Output: 3.141592653589793
Tip: This makes your code cleaner and faster since it doesn’t load unnecessary functions.
You can create your own custom module by saving a Python file (.py) and importing it:
Example: Create my_module.py
def greet(name):
return f"Hello, {name}!"
Now, import and use it in another script:
import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
A virtual environment (venv) is a separate space where you can install packages without affecting your system Python. This is useful for keeping projects isolated.
Steps to create a virtual environment:
python -m venv myenv # Creates a virtual environment named 'myenv'
Activate the virtual environment:
myenv\Scripts\activate
source myenv/bin/activate
Once activated, your terminal will show (myenv), meaning you’re inside the virtual environment.
Tip: Use deactivate to exit the virtual environment.
pip is Python’s package manager. It lets you install and manage external libraries.
Install a package:
pip install numpy
Install multiple packages from a requirements file:
pip install -r requirements.txt
Save installed packages to a file:
pip freeze > requirements.txt
Tip: Always use a virtual environment when working on projects to avoid package conflicts.
from module import function) to keep code clean.These are important skills for any Python interview.
These are the most commonly used data structures in Python. Each one has its own purpose, so let’s break them down in simple terms.
A list is like a shopping list—it keeps items in the same order, and you can add, remove, or change items anytime.
my_list = [1, 2, 3, 4] # A simple list
my_list.append(5) # Adds 5 to the end
print(my_list) # Output: [1, 2, 3, 4, 5]
Tip: Use .append() to add an item and .pop() to remove the last one.
my_list.pop() # Removes 5
A tuple is like your date of birth—it never changes. Once created, you cannot modify it.
my_tuple = (1, 2, 3) # A tuple
If you try to change it:
my_tuple[0] = 10 # ❌ This will cause an error!
Tip: Tuples are faster than lists, so use them when data won’t change.
A set is like a basket of apples—you can’t have duplicates, and the order doesn’t matter.
my_set = {1, 2, 3, 3} # Duplicate 3 is ignored
print(my_set) # Output: {1, 2, 3}
Tip: Use sets for removing duplicates from a list.
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
A dictionary is like a phonebook—you store keys (names) and values (phone numbers).
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict['name']) # Output: Alice
Tip: Use .keys() to get all keys and .values() to get all values.
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])
print(my_dict.values()) # Output: dict_values(['Alice', 25])
Sometimes, you need to store data in a specific order. That’s where stacks and queues come in.
A stack is like a stack of plates—you always remove the top one first (Last In, First Out).
stack = []
stack.append(1) # Push 1
stack.append(2) # Push 2
stack.pop() # Removes 2 (LIFO)
Tip: Use .append() to push and .pop() to remove the last item.
A queue is like a line at a ticket counter—the first person to enter is the first to leave.
Use collections.deque (better performance than lists).
from collections import deque
queue = deque()
queue.append(1) # Add to queue
queue.append(2)
queue.popleft() # Removes 1 (FIFO)
Tip: .append() adds to the queue, and .popleft() removes the first item.
These concepts often come up in coding interviews, so make sure to practice them!
Working with files is a must-have skill, whether you’re dealing with text, CSV, or JSON. Here’s a quick and practical breakdown of how to do it.
If you want to read a file’s content, use the "r" mode (read mode).
with open("file.txt", "r") as f:
content = f.read()
print(content) # Displays the file's content
Tip: Using with open(...) automatically closes the file, so you don’t need to worry about closing it manually.
If you need to write to a file, use the "w" mode (write mode).
with open("file.txt", "w") as f:
f.write("Hello, Python!")
Warning: "w" overwrites the file’s content. If you want to add new content instead of replacing, use "a" (append mode).
with open("file.txt", "a") as f:
f.write("\nAppending new line!")
If you’re working with large files, reading line by line is more efficient.
with open("file.txt", "r") as f:
for line in f:
print(line.strip()) # Removes extra spaces & newlines
Tip: .strip() removes unwanted spaces and \n characters at the end of each line.
CSV (Comma-Separated Values) files are common in data processing. Python’s csv module makes them easy to handle.
Reading a CSV file:
import csv
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row) # Each row is a list
Writing to a CSV file:
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
Tip: newline="" prevents extra blank lines in Windows when writing CSV files.
JSON (JavaScript Object Notation) is great for storing and transferring structured data. Python’s json module makes it easy.
Writing Python data to a JSON file:
import json
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as f:
json.dump(data, f) # Save JSON file
Reading a JSON file into Python:
with open("data.json", "r") as f:
data = json.load(f) # Load JSON file
print(data) # Output: {'name': 'Alice', 'age': 25}
Tip: If you need to convert Python objects to/from JSON strings (instead of files), use:
json_str = json.dumps(data) # Convert to JSON string
python_data = json.loads(json_str) # Convert back to Python dictionary
"r" for reading, “w” for writing, and “a” for appending.with open(...) to avoid file handling issues.Mastering file handling is crucial for working with real-world data.
Python lets you run multiple tasks simultaneously using threads and processes, but they work differently.
| Feature | Threads | Processes |
|---|---|---|
| Definition | A thread is a lightweight unit inside a process. | A process is an independent program in execution. |
| Memory | Threads share memory (faster but riskier). | Each process has its own memory (safer but uses more resources). |
| Speed | Faster since threads share the same space. | Slower due to separate memory and communication overhead. |
| Crash Impact | A crashing thread doesn’t affect others in the process. | If a process crashes, it dies completely. |
Example:
If you open Google Chrome, it starts as a process. Each tab runs as a separate process. Inside each tab, multiple threads handle tasks like rendering pages and downloading files.
Using threading Module
import threading
def print_numbers():
for i in range(5):
print(i)
t1 = threading.Thread(target=print_numbers)
t1.start() # Start the thread
t1.join() # Wait for the thread to finish
Creating a Process (Using multiprocessing Module)
import multiprocessing
def print_numbers():
for i in range(5):
print(i)
p1 = multiprocessing.Process(target=print_numbers)
p1.start() # Start the process
p1.join() # Wait for the process to finish
Key Difference:
When multiple threads try to modify the same data at the same time, things can go wrong! 😨 This is called a race condition.
Solution: Use Locks to prevent multiple threads from accessing the same resource at the same time.
Example Without Lock (Risky )
import threading
counter = 0
def increase():
global counter
for _ in range(1000000):
counter += 1
t1 = threading.Thread(target=increase)
t2 = threading.Thread(target=increase)
t1.start()
t2.start()
t1.join()
t2.join()
print("Final Counter:", counter) # The output is unpredictable 😬
Example With Lock (Safe )
import threading
counter = 0
lock = threading.Lock()
def increase():
global counter
for _ in range(1000000):
with lock: # Ensures only one thread changes 'counter' at a time
counter += 1
t1 = threading.Thread(target=increase)
t2 = threading.Thread(target=increase)
t1.start()
t2.start()
t1.join()
t2.join()
print("Final Counter:", counter) # Always correct ✅
Mastering Python terminology is a game-changer for technical interviews. Understanding key concepts like OOP, data structures, exception handling, and memory management helps you write clean, efficient code while impressing interviewers.
But memorization isn’t enough—practice is key! Work on real coding problems, explore Python’s built-in modules, and always think out loud when explaining solutions.
Keep sharpening your skills, stay curious, and approach every interview with confidence. Your next Python job is just one well-prepared answer away!
Official Python Docs – The ultimate reference for Python syntax, libraries, and best practices.
HackerRank – Python Challenges – Great for beginners to advanced coders.
CodeSignal – Simulated interview assessments to test your skills.
LinkedIn Jobs – Find Python-related job openings.
Turing – Remote Python developer jobs.
After debugging production systems that process millions of records daily and optimizing research pipelines that…
The landscape of Business Intelligence (BI) is undergoing a fundamental transformation, moving beyond its historical…
The convergence of artificial intelligence and robotics marks a turning point in human history. Machines…
The journey from simple perceptrons to systems that generate images and write code took 70…
In 1973, the British government asked physicist James Lighthill to review progress in artificial intelligence…
Expert systems came before neural networks. They worked by storing knowledge from human experts as…
This website uses cookies.