1. Python Glossary
Essential Python terminology explained:
Argument
A value passed to a function when it is called. Can be positional or keyword arguments.
Attribute
A value associated with an object, accessed using dot notation (object.attribute).
Class
A blueprint for creating objects, defining attributes and methods.
Decorator
A function that modifies the behavior of another function or class without changing its source code.
Dictionary
A mutable, unordered collection of key-value pairs.
Exception
An error that occurs during program execution, which can be caught and handled.
Function
A reusable block of code that performs a specific task.
Generator
A function that yields values one at a time, creating an iterator.
Immutable
An object that cannot be changed after creation (e.g., strings, tuples, numbers).
Iterator
An object that can be iterated over, returning items one at a time.
List
A mutable, ordered collection of items, defined with square brackets [].
Method
A function that belongs to an object or class.
Module
A file containing Python code (functions, classes, variables) that can be imported.
Mutable
An object that can be changed after creation (e.g., lists, dictionaries, sets).
Object
An instance of a class containing data (attributes) and code (methods).
Package
A directory containing multiple Python modules and an __init__.py file.
Parameter
A variable in a function definition that receives an argument value.
Slice
A portion of a sequence (list, string, tuple) accessed using [start:stop:step] syntax.
Tuple
An immutable, ordered collection of items, defined with parentheses ().
Variable
A name that refers to a value stored in memory.
2. Operators Reference
Arithmetic Operators
+ Addition (5 + 3 = 8)
- Subtraction (5 - 3 = 2)
* Multiplication (5 * 3 = 15)
/ Division (5 / 2 = 2.5)
// Floor Division (5 // 2 = 2)
% Modulus (5 % 2 = 1)
** Exponentiation (5 ** 2 = 25)
Comparison Operators
== Equal to (5 == 5 → True)
!= Not equal to (5 != 3 → True)
> Greater than (5 > 3 → True)
< Less than (5 < 3 → False)
>= Greater or equal (5 >= 5 → True)
<= Less or equal (3 <= 5 → True)
Logical Operators
and Both conditions must be True
(True and False → False)
or At least one condition must be True
(True or False → True)
not Negates the condition
(not True → False)
Assignment Operators
= Simple assignment (x = 5)
+= Add and assign (x += 3 → x = x + 3)
-= Subtract and assign (x -= 3 → x = x - 3)
*= Multiply and assign (x *= 3 → x = x * 3)
/= Divide and assign (x /= 3 → x = x / 3)
//= Floor divide and assign
%= Modulus and assign
**= Exponent and assign
Membership Operators
in Check if value exists in sequence
('a' in 'apple' → True)
not in Check if value doesn't exist
('z' not in 'apple' → True)
Identity Operators
is Check if two variables refer to same object
(x is y)
is not Check if two variables don't refer to same object
(x is not y)
4. String Methods
s = "Hello World"
# Case conversion
s.upper() # "HELLO WORLD"
s.lower() # "hello world"
s.capitalize() # "Hello world"
s.title() # "Hello World"
s.swapcase() # "hELLO wORLD"
# Search and replace
s.find("World") # 6 (index)
s.replace("World", "Python") # "Hello Python"
s.count("l") # 3
s.startswith("Hello") # True
s.endswith("World") # True
# Split and join
s.split() # ['Hello', 'World']
s.split("o") # ['Hell', ' W', 'rld']
", ".join(["a", "b"]) # "a, b"
# Whitespace handling
" hello ".strip() # "hello"
" hello ".lstrip() # "hello "
" hello ".rstrip() # " hello"
# Checking content
"123".isdigit() # True
"abc".isalpha() # True
"abc123".isalnum() # True
" ".isspace() # True
# Formatting
"Hello {}".format("World") # "Hello World"
f"Hello {name}" # f-string
"Hello".center(20, "-") # "-------Hello--------"
5. List Methods
lst = [1, 2, 3]
# Adding elements
lst.append(4) # [1, 2, 3, 4]
lst.insert(0, 0) # [0, 1, 2, 3, 4]
lst.extend([5, 6]) # [0, 1, 2, 3, 4, 5, 6]
# Removing elements
lst.remove(3) # Remove first occurrence of 3
lst.pop() # Remove and return last element
lst.pop(0) # Remove and return element at index 0
lst.clear() # Remove all elements
# Searching
lst.index(2) # Find index of first occurrence
lst.count(2) # Count occurrences of 2
# Sorting
lst.sort() # Sort in place (ascending)
lst.sort(reverse=True) # Sort descending
lst.reverse() # Reverse in place
# Copying
new_lst = lst.copy() # Shallow copy
# List comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]
6. Dictionary Methods
d = {'a': 1, 'b': 2}
# Accessing values
d['a'] # 1
d.get('a') # 1
d.get('c', 0) # 0 (default if key doesn't exist)
# Adding/updating
d['c'] = 3 # {'a': 1, 'b': 2, 'c': 3}
d.update({'d': 4}) # Add/update multiple items
# Removing
d.pop('a') # Remove and return value
d.popitem() # Remove and return last item
del d['b'] # Remove key 'b'
d.clear() # Remove all items
# Views
d.keys() # dict_keys(['a', 'b'])
d.values() # dict_values([1, 2])
d.items() # dict_items([('a', 1), ('b', 2)])
# Copying
new_d = d.copy() # Shallow copy
# Dictionary comprehension
squares = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
7. Built-in Functions
# Type conversion
int("123") # 123
float("3.14") # 3.14
str(42) # "42"
list("abc") # ['a', 'b', 'c']
tuple([1, 2]) # (1, 2)
set([1, 1, 2]) # {1, 2}
# Math functions
abs(-5) # 5
round(3.7) # 4
pow(2, 3) # 8 (2^3)
max([1, 5, 3]) # 5
min([1, 5, 3]) # 1
sum([1, 2, 3]) # 6
# Sequence functions
len([1, 2, 3]) # 3
sorted([3, 1, 2]) # [1, 2, 3]
reversed([1, 2, 3]) #
enumerate(['a', 'b']) # [(0,'a'), (1,'b')]
zip([1,2], ['a','b']) # [(1,'a'), (2,'b')]
# Iterators
range(5) # 0,1,2,3,4
range(1, 6) # 1,2,3,4,5
range(0, 10, 2) # 0,2,4,6,8
# Type checking
type(42) #
isinstance(42, int) # True
# I/O
print("Hello") # Output to console
input("Name: ") # Get user input
open("file.txt", "r") # Open file
# Others
all([True, True]) # True (all are True)
any([False, True]) # True (at least one is True)
map(int, ["1","2"]) # Apply function to each item
filter(lambda x: x>0, [-1,1]) # Filter items
8. File Operations
File Modes
'r' Read (default) - File must exist
'w' Write - Creates new file or overwrites existing
'a' Append - Adds to end of file
'x' Exclusive creation - Fails if file exists
'b' Binary mode (e.g., 'rb', 'wb')
't' Text mode (default)
'+' Read and write (e.g., 'r+', 'w+')
File Operations Examples
# Reading
with open('file.txt', 'r') as f:
content = f.read() # Read entire file
lines = f.readlines() # Read all lines as list
line = f.readline() # Read one line
# Writing
with open('file.txt', 'w') as f:
f.write("Hello\n") # Write string
f.writelines(["Line1\n", "Line2\n"])
# Appending
with open('file.txt', 'a') as f:
f.write("Appended line\n")
10. PEP 8 Style Guide
PEP 8 is Python's official style guide. Following it makes code more readable and maintainable.
Naming Conventions
# Variables and functions: snake_case
my_variable = 10
def my_function():
pass
# Classes: PascalCase
class MyClass:
pass
# Constants: UPPERCASE
MAX_SIZE = 100
PI = 3.14159
# Private variables: _leading_underscore
_internal_variable = 42
Indentation and Spacing
# Use 4 spaces per indentation level
def function():
if condition:
do_something()
# Two blank lines before top-level functions/classes
def function1():
pass
def function2():
pass
# One blank line between methods in a class
class MyClass:
def method1(self):
pass
def method2(self):
pass
Line Length and Imports
# Maximum line length: 79 characters
# Break long lines
result = some_function(
argument1, argument2,
argument3, argument4
)
# Imports at top of file, grouped:
# 1. Standard library
import os
import sys
# 2. Third-party
import numpy as np
# 3. Local
from mymodule import myfunction