learn.fttgsolutions.com · Cheat Sheets
Read. Transform. Automate.
Getting Started
| print() | print("Hello, World!") | Output a value to the console. |
| Variables | age = 18
name = "John" | Store data without declaring a type — Python infers it automatically. |
| input() | name = input("Enter your name: ") | Read a string from the user via the console. |
| type() | print(type(x)) | Return the data type of a variable. |
| Comment | # This is a comment | Single-line comment — Python ignores everything after the #. |
| Multiline comment | """ line 1
line 2 """ | Triple-quoted string used as a multiline comment or docstring. |
Data Types
| str | x = "Hello" | Text data. Use single or double quotes interchangeably. |
| int | x = 42 | Whole numbers, positive or negative, with no decimal point. |
| float | x = 3.14 | Numbers with a decimal point. |
| bool | x = True | Boolean value — either True or False. |
| list | x = [1, 2, 3] | Ordered, mutable sequence — items can be added, removed, or changed. |
| tuple | x = (1, 2, 3) | Ordered, immutable sequence — cannot be changed after creation. |
| dict | x = {"key": "value"} | Key-value mapping — keys must be unique and hashable. |
| set | x = {1, 2, 3} | Unordered collection of unique items. |
| int() | int("3") # → 3 | Cast a value to an integer. |
| float() | float("3.14") # → 3.14 | Cast a value to a float. |
| str() | str(42) # → "42" | Cast a value to a string. |
| bool() | bool(0) # → False | Cast a value to a boolean. 0, None, empty string/list/dict are all False. |
Arithmetic & Operators
| Addition | 10 + 30 # → 40 | Add two values. |
| Subtraction | 40 - 10 # → 30 | Subtract one value from another. |
| Multiplication | 50 * 5 # → 250 | Multiply two values. |
| Float division | 16 / 4 # → 4.0 | Divide and always return a float. |
| Integer division | 16 // 4 # → 4 | Divide and floor the result to an integer. |
| Modulo | 25 % 2 # → 1 | Return the remainder of a division. |
| Exponentiation | 5 ** 3 # → 125 | Raise a number to a power. |
| Compound assignment | counter += 10 | Shorthand for counter = counter + 10. Works with -, *, /, // etc. |
| and | a and b | True only if both a and b are truthy. |
| or | a or b | True if at least one of a or b is truthy. |
| not | not a | Invert the boolean value of a. |
| is | x is None | True if both variables point to the same object in memory. |
Strings
| Index access | s[0] # first char
s[-1] # last char | Access a character by position. Negative indices count from the end. |
| Slicing | s[2:5] | Extract a substring from index 2 up to (not including) index 5. |
| Slice from start | s[:4] | Slice from the beginning up to index 3. |
| Slice to end | s[2:] | Slice from index 2 to the end of the string. |
| Reverse string | s[::-1] | Return a reversed copy of the string using a -1 stride. |
| len() | len(s) | Return the number of characters in a string. |
| Concatenation | "spam" + "egg" # → "spamegg" | Join two strings end to end. |
| Repeat | "ha" * 3 # → "hahaha" | Repeat a string n times. |
| in operator | "spam" in "I like spam" # → True | Test whether a substring exists inside a string. |
| Loop characters | for c in "hello": print(c) | Iterate through each character in a string. |
| join() | "-".join(["a","b","c"]) # → "a-b-c" | Concatenate a list of strings with a separator. |
| split() | "a,b,c".split(",") | Split a string into a list on a delimiter. |
| strip() | " hi ".strip() # → "hi" | Remove leading and trailing whitespace. |
| replace() | "foo bar".replace("foo", "baz") | Return a copy of the string with a substring replaced. |
| lower() / upper() | s.lower() / s.upper() | Convert all characters to lowercase or uppercase. |
| endswith() | "hello!".endswith("!") # → True | Return True if the string ends with the given suffix. |
String Formatting
| f-string (basic) | f"Hello, {name}!" | Embed a variable directly in a string. Requires Python 3.6+. |
| f-string (expression) | f"{x} + 10 = {x + 10}" | Evaluate any expression inside the curly braces. |
| f-string (decimals) | f"{3.14159:.2f}" # → "3.14" | Format a float to a fixed number of decimal places. |
| f-string (zero pad) | f"{n:010}" # → "0000012345" | Pad a number with leading zeros to a given total width. |
| f-string (thousands) | f"{1000000:,.2f}" # → "1,000,000.00" | Format a number with comma thousand separators. |
| f-string (percentage) | f"{0.25:.0%}" # → "25%" | Format a float as a percentage. |
| f-string (binary) | f"{10:b}" # → "1010" | Format an integer as a binary string. |
| f-string (hex) | f"{200:x}" # → "c8" | Format an integer as a lowercase hexadecimal string. |
| format() method | "{} is {} years old".format(name, age) | Inject values into a string using positional placeholders. |
| % formatting | "%s is %d years old" % (name, age) | Old-style string formatting using the % operator. |
Lists
| Create list | li = [1, 2, 3] | Define a list with initial values. |
| From range | li = list(range(1, 11)) | Create a list of numbers from a range. |
| append() | li.append(4) | Add an element to the end of the list. |
| extend() | li.extend([5, 6, 7]) | Add all elements of another list to the end. |
| pop() | li.pop() # removes last
li.pop(0) # removes first | Remove and return an element by index (default: last). |
| del | del li[0] | Delete an element at a specific index. |
| Index access | li[0] # first
li[-1] # last | Access an element by position. Negative indices count from the end. |
| Slicing | li[1:4] # indices 1-3
li[::-1] # reversed | Extract a sub-list using start:stop:step notation. |
| sort() | li.sort() | Sort the list in place in ascending order. |
| reverse() | li.reverse() | Reverse the list in place. |
| count() | li.count(3) | Return the number of times a value appears in the list. |
| len() | len(li) | Return the number of elements in the list. |
| Repeat list | [0] * 5 # → [0,0,0,0,0] | Create a list by repeating elements n times. |
| List comprehension | [x**2 for x in range(10) if x % 2 == 0] | Build a new list by applying an expression to each item, with optional filtering. |
| filter() | list(filter(lambda x: x > 0, nums)) | Return only the elements for which the function returns True. |
Tuples & Sets
| Tuple | t = (1, 2, 3) | Ordered, immutable sequence. Cannot be modified after creation. |
| Tuple unpack | a, b, c = (1, 2, 3) | Unpack tuple values into individual variables. |
| Set | s = {1, 2, 3} | Unordered collection of unique items — duplicates are ignored. |
| set.add() | s.add(4) | Add a single element to the set. |
| set.remove() | s.remove(2) | Remove an element from the set (raises KeyError if not found). |
| Union | s1 | s2 | Return all unique elements from both sets. |
| Intersection | s1 & s2 | Return only elements that appear in both sets. |
| Difference | s1 - s2 | Return elements in s1 that are not in s2. |
Dictionaries
| Create dict | d = {"name": "John", "age": 30} | Define a dictionary with key-value pairs. |
| Access value | d["name"] # → "John" | Retrieve a value by its key. Raises KeyError if missing. |
| get() | d.get("age", 0) | Retrieve a value by key, returning a default if the key doesn't exist. |
| Add / update | d["email"] = "j@j.com" | Add a new key-value pair or overwrite an existing key. |
| update() | d.update({"city": "NYC"}) | Merge another dictionary into this one. |
| del key | del d["age"] | Remove a key-value pair from the dictionary. |
| keys() | d.keys() | Return a view of all keys in the dictionary. |
| values() | d.values() | Return a view of all values in the dictionary. |
| items() | d.items() | Return a view of all (key, value) pairs. |
| Loop dict | for k, v in d.items():
print(k, v) | Iterate over key-value pairs. |
| Dict comprehension | {k: v*2 for k, v in d.items()} | Build a new dictionary using an expression over existing key-value pairs. |
| in operator | "name" in d # → True | Check whether a key exists in the dictionary. |
Control Flow
| if / elif / else | if x > 10:
...
elif x == 10:
...
else:
... | Branch execution based on one or more conditions. |
| Ternary operator | result = "a" if a > b else "b" | Assign a value based on a condition in a single line. |
| pass | if x: pass | Do nothing — placeholder where a statement is syntactically required. |
Loops
| for loop | for item in my_list:
print(item) | Iterate over every item in an iterable. |
| while loop | while x < 10:
x += 1 | Repeat a block as long as a condition is true. |
| range() | range(5) # 0-4
range(2, 8) # 2-7
range(0, 10, 2) # 0,2,4,6,8 | Generate a sequence of numbers with optional start, stop, and step. |
| enumerate() | for i, val in enumerate(items): | Loop with both the index and the value available. |
| zip() | for a, b in zip(list1, list2): | Loop over two or more iterables in parallel. |
| break | if x == 5: break | Exit the loop immediately. |
| continue | if x == 5: continue | Skip the rest of the current iteration and move to the next. |
| for / else | for n in nums:
if n > 100: break
else:
print("not found") | The else block runs only if the loop finished without hitting a break. |
Functions
| Define function | def greet(name):
return f"Hello, {name}" | Define a reusable block of code that optionally returns a value. |
| Default argument | def add(x, y=10):
return x + y | Provide a fallback value used when the argument is omitted. |
| *args | def total(*args):
return sum(args) | Accept any number of positional arguments as a tuple. |
| **kwargs | def show(**kwargs):
print(kwargs) | Accept any number of keyword arguments as a dictionary. |
| Multiple return | def swap(a, b):
return b, a
x, y = swap(x, y) | Return a tuple and unpack it into separate variables. |
| Lambda | double = lambda x: x * 2 | A small anonymous function defined in a single expression. |
| map() | list(map(lambda x: x*2, nums)) | Apply a function to every element of an iterable. |
Classes & OOP
| Define class | class Dog:
def __init__(self, name):
self.name = name | Define a class with a constructor that initialises instance attributes. |
| Instantiate | my_dog = Dog("Rex") | Create an instance of a class. |
| Method | def bark(self):
print("Woof!") | A function defined inside a class. self refers to the current instance. |
| Class variable | class Dog:
species = "Canis lupus" | A variable shared across all instances of the class. |
| Inheritance | class Poodle(Dog):
pass | Create a subclass that inherits all attributes and methods from the parent. |
| super() | super().__init__(name) | Call a method from the parent class — commonly used in __init__. |
| __repr__() | def __repr__(self):
return self.name | Define how the object is displayed as a string (e.g. in print or repr()). |
| Custom exception | class MyError(Exception):
pass | Create a custom exception type by inheriting from Exception. |
File Handling
| Read file | with open("file.txt", "r") as f:
contents = f.read() | Open a file and read its entire contents as a string. |
| Read line by line | with open("file.txt") as f:
for line in f:
print(line) | Iterate over each line without loading the whole file into memory. |
| Write file | with open("file.txt", "w") as f:
f.write("hello") | Write a string to a file, creating it if it doesn't exist. |
| Write JSON | import json
with open("f.json", "w") as f:
json.dump(data, f) | Serialise a Python object to a JSON file. |
| Read JSON | with open("f.json") as f:
data = json.load(f) | Deserialise a JSON file back into a Python object. |
| Delete file | import os
os.remove("file.txt") | Delete a file from the filesystem. |
| Check file exists | if os.path.exists("file.txt"):
os.remove("file.txt") | Safely check if a file exists before acting on it. |
Modules
| import | import math
math.sqrt(16) # → 4.0 | Import an entire module and access its members with dot notation. |
| from import | from math import ceil, floor | Import specific names from a module directly into the current namespace. |
| import as | import numpy as np | Import a module under a shorter alias. |
| dir() | dir(math) | List all attributes and functions available in a module. |
Error Handling
| try / except | try:
x = 1 / 0
except ZeroDivisionError as e:
print(e) | Catch a specific exception and handle it gracefully. |
| Multiple exceptions | except (TypeError, ValueError): | Handle several exception types with a single except clause. |
| else clause | else:
print("no error") | Execute this block only if no exception was raised in try. |
| finally clause | finally:
print("always runs") | Always execute this block — used for cleanup like closing files. |
| raise | raise ValueError("bad input") | Manually trigger an exception. |
Generators & Advanced
| Generator function | def evens(n):
for i in range(n):
if i % 2 == 0: yield i | Use yield to produce values lazily one at a time instead of building a full list. |
| Generator expression | squares = (x**2 for x in range(10)) | Compact lazy generator — like a list comprehension but uses parentheses. |
| heapq (min-heap) | import heapq
heapq.heapify(lst)
heapq.heappush(lst, 5)
smallest = heapq.heappop(lst) | Turn a list into a min-heap. Push and pop maintain the heap property in O(log n). |
| deque | from collections import deque
q = deque([1,2,3])
q.appendleft(0)
q.popleft() | Double-ended queue with O(1) appends and pops from both ends — good for stacks and queues. |
| enumerate (start) | for i, line in enumerate(lines, start=1):
print(i, line) | Loop with a counter that can start at any number. |