The complete cram sheet — fundamentals, data types & operators, functions, classes & OOP, files & exceptions, and NumPy. Every concept, mnemonic, and code pattern from the six decks, in one place.
Python is a high-level, interpreted, general-purpose and dynamic programming language that focuses on code readability.
Its syntax lets programmers write code in fewer steps than Java or C++.
Four words to remember Python by:
A–Z and a–z
0 to 9
space + - / ( ) [ ] = != < > , ' " $ # ; : ? &
Blank space, horizontal tab, vertical tab, carriage return
Python can process all 256 ASCII and Unicode characters.
| K | Keywords — reserved words with special meaning |
| I | Identifiers — names you give to things |
| L | Literals — fixed constant values |
| O | Operators — trigger a computation |
| P | Punctuators — separators like brackets, commas |
Keywords (reserved words) have a special, predefined meaning in the Python interpreter. Because of that, they cannot be used as identifiers.
✓ Valid
Myfile1 · DATE9_7_8 · y3m9d3 · _xs · MYFILE · _FXd
✗ Invalid
MY-REC · 28dre · break · elif · false · del
| S | String literals — text in quotes |
| N | Numeric literals — int, float, complex |
| B | Boolean literals — True / False |
| N | None — the special "no value" literal |
| C | Collections — tuple, list, etc. |
A sequence of letters in quotes. Python accepts both forms: 'Hello' = "Hello".
Begins and ends on one line.
Item = "Computer"Spread across lines using a backslash \ to continue.
Item = 'Key\ board'
Indexing works forward (0,1,2…) and backward (-1,-2…):
>>> s = "Hello Python" >>> s[0] # 'H' (first) >>> s[-1] # 'n' (last) >>> s[len(s)-1] # 'n' (len() = length of string)
| Seq | Meaning |
|---|---|
\\ | Back slash |
\' | Single quote |
\" | Double quote |
\a | ASCII bell |
\b | ASCII backspace |
\f | ASCII formfeed |
| Seq | Meaning |
|---|---|
\n | New line |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\x | 16-bit hex value |
\ooo | Octal value (3 digits) |
| I | int — whole numbers, +ve or −ve, unlimited length |
| F | float — real values with a fractional part |
| C | complex — complex numbers (e.g. 1j) |
| Base | Prefix | Example |
|---|---|---|
| Decimal | none | 255 |
| Octal (8) | 0o | 0o377 |
| Hex (16) | 0x / 0X | 0xFF |
| Binary (2) | 0b / 0B | 0b1010 |
Convert an int to its string representation with these built-ins:
oct(7) # '0o7' hex(2572) # hexadecimal string bin(12) # binary string
[ ] ( ) { } , ; : * … = #
Brackets, parentheses, braces, comma, semicolon, colon, asterisk, ellipsis, equal sign, pound sign.
Non-executable statements.
The expression on the Left-Hand Side of =.
The expression on the Right-Hand Side of =.
# same value to many variables a = b = c = d = e = 10 # many values to many variables p, q, r = 5, 10, 15 # swap (no temp variable needed) p, q = q, p # now p=10, q=5
Expressions separated by commas evaluate left to right. With y, y = 12, 15 it assigns y=12 then y=15, so y ends as 15.
A variable pointing to one type can be re-pointed to a value of a different type — that's dynamic typing.
x = 10 print(x) x = "Hello World" # perfectly legal # caution: types must make sense for the operation x = 'day' y = x / 2 # Error! a string can't be divided # type() reveals the current type type(10) # <class 'int'> type(20.4) # <class 'float'> type("Hi") # <class 'str'>
A built-in function that reads a value typed by the user. Syntax: variable = input(message). It always returns a string, so wrap it in int() / float() / complex() to convert.
p = input("Enter the value") age = int(input("Enter age")) # to integer sal = float(input("Enter salary")) # to float
Prints any number of values separated by commas. Full signature:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
| Param | Role |
|---|---|
*objects | One or more values to print (* = many) |
sep | Separator between objects. Default: ' ' |
end | Printed at the very end. Default: '\n' |
file | Output target. Default: screen (sys.stdout) |
flush | Force-flush the stream. Default: False |
print("Python is fun.") a = 5 print("a =", a) # a = 5 print("a = \n", a) # newline before the value
# 1. directly in the command line >>> print("Hello, World!") Hello, World! # 2. as a .py file C:\Users\Name> python myfile.py
Indentation = the spaces at the start of a line. In most languages it's cosmetic; in Python it's required — it defines a block of code.
if 5 > 2: print("Five is greater than two!")
Python has no declaration command — a variable is born the moment you assign a value.
x = 5 y = "Hello, World!"
x = str(3) # '3' y = int(3) # 3 z = float(3) # 3.0
| C | Camel — myVariableName |
| P | Pascal — MyVariableName |
| S | Snake — my_variable_name |
| T | Text — str |
| N | Numeric — int, float, complex |
| S | Sequence — list, tuple, range |
| M | Mapping — dict |
| S | Set — set, frozenset |
| B | Boolean — bool |
| B | Binary — bytes, bytearray, memoryview |
| N | None — NoneType |
Whole number, +ve/−ve, no decimals, unlimited length.
x = 1Number with one or more decimals, +ve/−ve.
y = 2.8Has an imaginary part written with j.
z = 1jStrings use single or double quotes — 'hello' = "hello" — and print with print().
a = "Hello, World!" print(a.upper()) # HELLO, WORLD! print(a.lower()) # hello, world! b = " Hello, World! " print(b.strip()) # "Hello, World!" (removes whitespace) print(a.replace("H", "J")) # Jello, World! print(a.split(",")) # ['Hello', ' World!']
Concatenation — combine strings with + (add a space manually):
a = "Hello"; b = "World" c = a + " " + b # "Hello World"
| Method | Does |
|---|---|
upper() / lower() | Convert case |
capitalize() | First character to upper case |
title() | First char of each word to upper |
swapcase() | Lower↔upper for every char |
strip() / lstrip() / rstrip() | Trim whitespace (both/left/right) |
replace(a, b) | Swap a specified value for another |
split(sep) | Split into a list at the separator |
join() | Join an iterable onto the string |
find() / index() | Position of a value |
count() | How many times a value occurs |
startswith() / endswith() | True if string starts/ends with value |
isalnum() / isalpha() / isdigit() | True if all chars match the test |
format() | Insert specified values into a string |
zfill(n) | Pad the front with 0s |
Python ships ~45 string methods total — the ones above are the high-yield set.
Booleans represent one of two values: True or False. When you compare two values, Python evaluates the expression and returns a Boolean.
print(10 > 9) # True print(10 == 9) # False print(10 < 9) # False
| A | Arithmetic — math |
| A | Assignment — assign values |
| C | Comparison — compare two values |
| L | Logical — combine conditions |
| I | Identity — same object? |
| M | Membership — is it inside? |
| B | Bitwise — compare binary bits |
| Op | Name |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus (remainder) |
** | Exponentiation |
// | Floor division |
| Op | Name |
|---|---|
== | Equal |
!= | Not equal |
> | Greater than |
< | Less than |
>= | Greater or equal |
<= | Less or equal |
| Op | True when… |
|---|---|
and | both are true |
or | one is true |
not | reverses result |
| Op | True when… |
|---|---|
is | same object |
is not | not same object |
Compares memory location, not just equality.
| Op | True when… |
|---|---|
in | value is present |
not in | value is absent |
Assignment — shorthand for "do then store":
= += -= *= /= %= //= **= &= |= ^= >>= <<= :=
e.g. x += 3 is the same as x = x + 3. The := "walrus" assigns inline.
Bitwise — operate on binary bits:
| Op | Name |
|---|---|
& | AND |
| | OR |
^ | XOR |
~ | NOT (invert) |
<< | Zero-fill left shift |
>> | Signed right shift |
print((6+3) - (6+3)) # 0 → () first print(100 + 5 * 3) # 115 → * before +
| Level | Operators |
|---|---|
| Highest | ( ) parentheses |
** exponentiation | |
+x -x ~x unary | |
* / // % | |
+ - | |
<< >> shifts | |
& then ^ then | | |
| comparison / identity / membership | |
not → and → or |
def my_function(): print("Hello from a function")
def my_function(): print("Hello from a function") my_function() # runs it
def greet(): print('Hello World!')
The variable listed inside the parentheses in the function definition.
Hook: Parameter = the Plan.
The value that is sent to the function when it's called. Often shortened to args.
Hook: Argument = what Arrives.
def my_function(fname): # fname = parameter print(fname + " Refsnes") my_function("Emil") # "Emil" = argument my_function("Tobias")
Number of arguments: by default a call must pass exactly as many arguments as there are parameters — not more, not fewer, or you get an error.
Unknown number of arguments? Put one * before the parameter. The function receives a tuple.
def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus")
Send values as key = value. Order then doesn't matter.
def my_function(child3, child2, child1): print("The youngest is " + child3) my_function(child1="Emil", child2="Tobias", child3="Linus")
Unknown number of keyword args? Put two ** before the parameter. The function receives a dictionary.
def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname="Tobias", lname="Refsnes")
If no argument is passed, the default is used.
def my_function(country="Norway"): print("I am from " + country) my_function() # I am from Norway my_function("Brazil")
Any data type can be passed; it stays that type inside.
def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits)
Args before / must be positional.
def f(x, /): print(x) f(3)
Args after * must be keyword.
def f(*, x): print(x) f(x=3)
Before / positional, after * keyword.
def f(a,b,/,*,c,d): print(a+b+c+d) f(5,6,c=7,d=8)
def my_function(x): return 5 * x print(my_function(3)) # 15 print(my_function(5)) # 25
A definition can't be empty. If you need a placeholder, use pass to avoid an error.
def myfunction(): pass
A function is a reusable block of code that performs a specific task — it helps organize code and avoid repetition.
Without a function (repeats)
print('Hello') print('Hello') print('Hello')
With a function (reusable)
def greet(): print('Hello')
Runs immediately, top to bottom, once.
a = 33 # store 33 b = 200 # store 200 if b > a: # check 200 > 33 → True print("b is greater than a")
✗ No reuse · ✗ no structure · ✗ no grouping of logic · runs once only.
def compare(a, b): if b > a: print("b is greater than a") compare(33, 200)
| Procedural | Function version |
|---|---|
| Runs immediately | Doesn't run until called |
| Uses fixed values | Accepts different values |
| Cannot easily reuse | Reuse many times |
| No name for the logic | Groups logic under a name |
class Student: def __init__(self, name, age): self.name = name self.age = age
class Student: def __init__(self, name): self.name = name def greet(self): print('Hi, I am ' + self.name) student1 = Student('Carlos') student1.greet() # Hi, I am Carlos
student1 = Student('Ana', 20) print(student1.name) # Ana print(student1.age) # 20
class Car: def __init__(self, brand, color): self.brand = brand self.color = color def start(self): print(self.brand + ' is starting...') car1 = Car('Toyota', 'Red') car2 = Car('Honda', 'Blue') car1.start() # Toyota is starting...
| C | Classes — the blueprints |
| O | Objects — instances of classes |
| M | Methods — functions inside classes |
| O | Organized code |
| M | Maintainable — easy to maintain |
| R | Reusable code |
| R | Real-world modeling |
OOP is a programming style that uses classes, objects, and methods to organize large programs.
One-line summary: Function → reusable block · Class → blueprint/template · Object → instance of a class · OOP → organizing a program using objects.
| P | Permanent storage — survives after the program ends (unlike variables) |
| D | Data sharing — move data between programs/systems |
| L | Large datasets — handle data too big for memory |
| C | Config & logging — store settings, log activity for debugging |
Open a file before using it; close it with close() afterward to free resources.
| Mode | Name | Behavior |
|---|---|---|
r | Read | File must already exist |
w | Write | Creates new / overwrites existing (old content deleted!) |
a | Append | Adds to the end, keeps old content |
r+ | Read/Write | Both reading and writing |
file = open('data.txt', 'r') print(file.read())
Gets all content.
file = open('data.txt', 'w') file.write('Hello World')
Overwrites — use carefully!
file = open('data.txt', 'a') file.write(' New text') import os os.remove('data.txt')
Guarantees the file always closes, even if an error happens. Cleaner and more "Pythonic".
with open('data.txt') as file: print(file.read()) # auto-closed here
| Method | Returns |
|---|---|
read() | Entire file as one string |
readline() | One line at a time |
readlines() | All lines as a list |
try: file = open('data.txt') except: print('File not found')
| I | Introduction to NumPy |
| C | Creating arrays |
| I | Indexing |
| S | Slicing |
| D | Datatypes |
| R | Random |
| U | ufunc (universal functions) |
Build from Python lists; supports 1D, 2D, and multi-dimensional arrays. Helpers: zeros(), ones(), arange().
import numpy as np arr1 = np.array([1,2,3]) arr2 = np.zeros((2,2)) arr3 = np.arange(1,10) print(arr1)
Zero-based; can reach rows/columns in 2D arrays.
arr = np.array([10,20,30]) print(arr[0]) # 10
Extract parts with start:end:step.
arr = np.array([1,2,3,4,5]) print(arr[1:4]) # [2 3 4]
Arrays have fixed dtypes (int, float, bool, string). Check with .dtype.
arr = np.array([1,2,3]) print(arr.dtype)
Generate random numbers — great for simulations & ML. rand(), randint(), choice().
x = np.random.randint(1, 100) print(x)
Fast, element-wise math operations: add(), subtract(), multiply(), sin().
a = np.array([1,2,3]) b = np.array([4,5,6]) print(np.add(a, b)) # [5 7 9]
| Topic | # | Key | Phrase |
|---|---|---|---|
| Tokens / Lexical Units | 5 | K I L O P | "Keep It Logical, Or Panic" |
| Literals | 5 | S N B N C | "Smart Nerds Build Neat Code" |
| Numeric types | 3 | I F C | "I Find Complexity" |
| Data Type categories | 8 | T N S M S B B N | "Ten New Students Make Some Big Brilliant Notes" |
| Multi-word naming | 3 | C P S | Camel · Pascal · Snake |
| Operator groups | 7 | A A C L I M B | "All Animals Can Leap Into Muddy Bogs" |
| OOP building blocks | 3 | C O M | Classes · Objects · Methods |
| Why OOP matters | 4 | O M R R | "Organized Means Reusable & Real" |
| Why file handling matters | 4 | P D L C | "Please Don't Lose Code" |
| NumPy lesson topics | 7 | I C I S D R U | "I Can Instantly Slice Data Really Ultrafast" |
| Question | Answer |
|---|---|
| Python is high-level, interpreted, general-purpose, and… | Dynamic (focuses on code readability) |
| 5 types of tokens | Keywords, Identifiers, Literals, Operators, Punctuators |
| Reserved words that can't be identifiers | Keywords |
| Max line length in Python | 79 characters |
| Statement terminator symbol | None — Python uses no terminator |
| EOL stands for | End Of Line |
| Triple-quoted comment is called | Docstring |
| Re-pointing a variable to a new type is | Dynamic typing |
| Function to check a value's type | type() |
| input() always returns a | String (cast with int()/float()) |
| 8 data type categories | Text, Numeric, Sequence, Mapping, Set, Boolean, Binary, None |
| 3 numeric types | int, float, complex |
| 7 operator groups | Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise |
| Highest precedence | Parentheses ( ) |
is vs == | is → same object (memory); == → equal value |
| Keyword to define a function | def |
| Parameter vs Argument | Parameter = in definition; Argument = value sent at call |
| One * vs two ** before a parameter | *args → tuple; **kwargs → dictionary |
| Symbol for positional-only / keyword-only | , / (positional) · *, (keyword) |
| Empty-body placeholder keyword | pass |
| Class vs Object | Class = blueprint; Object = instance |
| The constructor method | __init__ |
self refers to | The current object |
| 3 OOP building blocks | Classes, Objects, Methods |
| 4 file modes | r (read), w (write/overwrite), a (append), r+ (read/write) |
| Mode that deletes old content | w (write) |
| Statement that auto-closes a file | with |
| 3 read methods | read(), readline(), readlines() |
| Handle errors with | try / except |
| NumPy stands for | Numerical Python |
| NumPy is faster than | Python lists |
| ufunc means | Universal Functions |
| Slicing syntax | start:end:step |