🐍 PYTHON: --------------------------------------------------------------------------------------------------------------------------------------------------- 🐍 Instructions / Commands / Verbs / Functions / Keywords / Methods / Actions --------------------------------------------------------------------------------------------------------------------------------------------------- 📦 import Import modules or specific attributes import math 🔧 def Define a function def greet(name): print("Hello", name) 🔙 return Return a value from a function return x + y 🛠️ try Start a try block for exception handling try: x=1/0 ❓ if If conditional statement if x > 0: 🔄 elif Else-if conditional branching elif x == 0: ❎ else Else conditional branch else: ⚠️ except Exception handler block except ZeroDivisionError: 🔁 while While loop while x < 5: 🔄 for For loop for i in range(3): 🔍 in Membership test in loops and conditions if 'a' in my_str: 📤 from Import specific attributes from a module from os import path 📝 pass No operation placeholder pass 🚫 break Break out of a loop break 🔜 continue Continue to next loop iteration continue 📣 print Output to console print("Hello world") ⬆️ raise Raise an exception raise ValueError("Wrong value") 🧪 assert Assert a condition for debugging assert x > 0, "Must be positive" 🔒 with Context manager (resource handling) with open('file.txt') as f: 🗑️ del Delete an object or variable del my_var 👫 global Declare a global variable inside a function global count 🔐 nonlocal Declare a nonlocal variable in nested scopes nonlocal total 🧮 lambda Create anonymous functions f = lambda x: x**2 📚 yield Yield value from generator function yield i 🎛️ async Define an asynchronous function async def fetch(): ⏳ await Wait for an async function to complete result = await fetch() 🧰 try...except...finally Try block w/ exception handler and cleanup final block try: ... 👉 else with loops Optional else block for loops if no break for i in x: ... else: print("Done") 📦 import as Import module with alias import numpy as np 📄 open Open a file or resource open('test.txt', 'r') 🪝 __init__ Constructor method in classes def __init__(self, val): 🏗️ class Define a class class Person: ⚙️ def __str__ String representation method of a class def __str__(self): ⚙️ def __repr__ Official string representation method of a class def __repr__(self): ⚙️ def __call__ Make object callable def __call__(self): 🔄 for...else For loop with optional else clause if no break for i in l: ... else: print("No break") ⬇️ try...else Try block with else if no exception try: ... else: print("No error") 🎯 assert with message Assert with optional error message assert x != 0, "Zero not allowed" 🧩 isinstance Check object type isinstance(obj, int) 🧪 type Get type of an object type(x) ✂️ slice Slice notation for sequences seq[2:5] 🔢 range Generate sequence of numbers range(5) 🧱 list Create list my_list = [1,2,3] 📑 tuple Create tuple my_tuple = (1, 2) 🔒 set Create set my_set = {1,2,3} 🌍 dict Create dictionary my_dict = {'a':1} 🧹 delattr Delete attribute of objects delattr(obj, 'attr') 📋 setattr Set attribute of objects setattr(obj, 'attr', val) 🧩 getattr Get attribute of objects getattr(obj, 'attr') 🕵️‍♂️ eval Evaluate string as Python expression eval('3 + 5') 📊 exec Execute string as Python code exec('print("Hi")') 🧱 list comprehension Concise list creation [x*2 for x in range(5)] 🧊 generator expression Create generator expression (x*2 for x in range(5)) 🔧 decorator Modify functions/classes with syntactic sugar @staticmethod 💣 raise from Re-raise exceptions with explicit cause raise ValueError from e 🔗 chained comparisons Compare multiple values 1 < x < 10 🚦 conditional expressions # Ternary if expression x = a if cond else b 🦾 walrus operator Assignment expression inside expressions if (n := len(x)) > 10: 💾 file handling keywords File open/read/write/close with open('f.txt') as file: 📑 match case Structural pattern matching (Python 3.10+) match x: case 1: ... --------------------------------------------------------------------------------------------------------------------------------------------------- 📑 Python Built-in Functions --------------------------------------------------------------------------------------------------------------------------------------------------- 〰️ abs() Return absolute value abs(-7) # 7 🩺 all() Check if all items are true all([True, True]) # True 🔍 any() Check if any item is true any([False, True]) # True 🅱️ ascii() Return ASCII representation of object ascii("é") # "'\\xe9'" 🐦 bin() Convert int to binary string bin(3) # '0b11' 🔢 bool() Convert to Boolean bool(0) # False 🏗️ breakpoint() Enter debugger breakpoint() 🧱 bytearray() Mutable array of bytes bytearray(b"Hi") 💠 bytes() Immutable bytes object bytes([1,2,3]) 🔡 callable() Check if object is callable callable(len) # True 📊 chr() Convert int to Unicode char chr(65) # 'A' 📝 classmethod() Declare class method @classmethod ⚖️ compile() Compile source to code object compile("x=5", "", "exec") ⊂ complex() Create complex number complex(1, 2) 📋 delattr() Delete object attribute delattr(obj, 'attr') 🌍 dict() Create dict dict(a=1, b=2) 🌊 dir() List attributes and methods dir([]) 🖇️ divmod() Quotient and remainder divmod(5, 2) # (2, 1) 👁️ enumerate() Enumerate iterable list(enumerate(['a','b'])) # [(0,'a'),(1,'b')] ☑️ eval() Evaluate string expression eval("1+2") # 3 📤 exec() Execute Python code string exec("print('hi')") 🧾 filter() Filter iterable by function list(filter(lambda x: x>0, [-1,0,1])) 📈 float() Convert to float float("2.5") # 2.5 📜 format() Format a value format(123, "06") 🧰 frozenset() Immutable set frozenset({1,2}) 🧩 getattr() Get object attribute getattr(obj, 'attr', None) 🛑 globals() Get global symbol table globals() 🧱 hasattr() Check if object has attribute hasattr(obj, 'attr') 🧮 hash() Get hash of object hash("abc") 🎯 help() Show help documentation help(abs) 🏠 hex() Convert to hex string hex(255) # '0xff' 🆔 id() Get object memory id id(obj) 🏗️ input() Read input from user input("Enter:") 🔣 int() Convert to int int("5") 📁 isinstance() Check object type isinstance(5, int) 🧬 issubclass() Check class inheritance issubclass(bool, int) 📍 iter() Get iterator iter([1,2]) 🧪 len() Get length of object len([1,2]) 📦 list() Create list list((1,2)) 📤 locals() Get local symbol table locals() 🔗 map() Map function over iterable list(map(str, [1,2])) 🧩 max() Max element max(1, 2, 3) ➖ min() Min element min([1, 2, 3]) 🧑‍💻 next() Next iterator item next(iter([1,2])) ⛔ object() Base object class object() 🎨 oct() Convert to octal string oct(8) # '0o10' 📄 open() Open file open("file.txt") ⏪ ord() Unicode code of char ord("A") # 65 🔑 pow() Power calculation pow(2,3) # 8 📦 print() Print output print("Hello") 🏷️ property() Create property property(fget) 🎲 range() Range of numbers range(5) 🗑️ repr() String representation repr("abc") 🔄 reversed() Reverse iterator list(reversed([1,2,3])) 🧊 round() Round number round(3.14159, 2) # 3.14 🔒 set() Create set set([1,2]) 🏗️ setattr() Set attribute setattr(obj, 'attr', 3) 📑 slice() Slice object slice(1,5) 🗂️ sorted() Sorted iterable sorted([3,1,2]) 📀 staticmethod() Create static method @staticmethod 🧩 str() Convert to string str(123) 🧱 sum() Sum iterable sum([1,2]) ✂️ super() Access superclass super() 📑 tuple() Create tuple tuple([1,2]) 📝 type() Get object type type(5) 📍 vars() Get __dict__ attribute vars(obj) 🎤 zip() Zip iterables list(zip([1,2], ['a','b'])) ⚡ __import__() Import module dynamically __import__('math') --------------------------------------------------------------------------------------------------------------------------------------------------- ✨ String Methods (str) --------------------------------------------------------------------------------------------------------------------------------------------------- 🔡 .capitalize() Capitalize first char "hello".capitalize() 🔡 .casefold() Casefold string (lowercase) "ß".casefold() 🔡 .center(width, fillchar) Center string with padding "cat".center(5, '*') 🔡 .count(sub[, start, end]) Count occurrences "hello".count('l') 🔡 .encode(encoding, errors) Encode string "abc".encode('utf-8') 🔡 .endswith(suffix[, start, end]) Ends with substring "hello".endswith('o') 🔡 .expandtabs(tabsize) Expand tabs "a\tb".expandtabs(2) 🔡 .find(sub[, start, end]) Find substring "hello".find('e') 🔡 .format(*args, **kwargs) Format string "{} {}".format("hi", 2) 🔡 .format_map(mapping) Format using mapping "{name}".format_map({'name':'Tom'}) 🔡 .index(sub[, start, end]) Find substring, raises if missing "hello".index('e') 🔡 .isalnum() Check if alphanumeric "abc123".isalnum() 🔡 .isalpha() Check if alphabetic "abc".isalpha() 🔡 .isascii() Check if ASCII chars only "abc".isascii() 🔡 .isdecimal() Check if decimal digit "123".isdecimal() 🔡 .isdigit() Check if digits only "123".isdigit() 🔡 .isidentifier() Check valid identifier "var_1".isidentifier() 🔡 .islower() Check all lowercase "abc".islower() 🔡 .isnumeric() Check numeric "123".isnumeric() 🔡 .isprintable() Check printable chars "abc\n".isprintable() 🔡 .isspace() Check if whitespace only " \t\n".isspace() 🔡 .istitle() Check title casing "Hello".istitle() 🔡 .isupper() Check all uppercase "ABC".isupper() 🔡 .join(iterable) Join with string separator ",".join(['a','b']) 🔡 .ljust(width, fillchar) Left justify string "cat".ljust(5, '*') 🔡 .lower() Convert to lowercase "ABC".lower() 🔡 .lstrip(chars) Strip left chars " abc".lstrip() 🔡 .partition(sep) Split at first sep "a,b,c".partition(',') 🔡 .removeprefix(prefix) Remove prefix "Test".removeprefix("Te") 🔡 .removesuffix(suffix) Remove suffix "Test".removesuffix("st") 🔡 .replace(old, new[, count]) Replace substrings "aabb".replace('a','c') 🔡 .rfind(sub[, start, end]) Find last occurrence "hello".rfind('l') 🔡 .rindex(sub[, start, end]) Find last occurrence, raise if miss "hello".rindex('l') 🔡 .rjust(width[, fillchar]) Right justify string "cat".rjust(5, '*') 🔡 .rpartition(sep) Split at last sep "a,b,c".rpartition(',') 🔡 .rsplit(sep, maxsplit) Split from right "a,b,c".rsplit(',',1) 🔡 .rstrip(chars) Strip right chars " abc ".rstrip() 🔡 .split(sep, maxsplit) Split string "a,b,c".split(',') 🔡 .splitlines(keepends) Split lines "a\nb\n".splitlines() 🔡 .startswith(prefix[, start, end]) Check prefix "abc".startswith('a') 🔡 .strip(chars) Strip chars on both ends " abc ".strip() 🔡 .swapcase() Swap case "aBc".swapcase() 🔡 .title() Title case "a bc".title() 🔡 .translate(table) Translate using mapping "abc".translate(str.maketrans('a','b')) 🔡 .upper() Convert to uppercase "abc".upper() 🔡 .zfill(width) Zero fill string "42".zfill(5) --------------------------------------------------------------------------------------------------------------------------------------------------- 🧱 List Methods (list) --------------------------------------------------------------------------------------------------------------------------------------------------- 🧱 .append(x) Add element to end lst.append(5) 🧱 .clear() Remove all elements lst.clear() 🧱 .copy() Return shallow copy lst.copy() 🧱 .count(x) Count occurrences lst.count(3) 🧱 .extend(iterable) Extend list with iterable lst.extend([4,5]) 🧱 .index(x[, start, end]) Get index of element lst.index(3) 🧱 .insert(i, x) Insert element at position lst.insert(0, 10) 🧱 .pop([i]) Remove and return element lst.pop() 🧱 .remove(x) Remove first occurrence lst.remove(3) 🧱 .reverse() Reverse list in-place lst.reverse() 🧱 .sort(key=None, reverse=False) Sort list lst.sort() --------------------------------------------------------------------------------------------------------------------------------------------------- 🌍 Dict Methods (dict) --------------------------------------------------------------------------------------------------------------------------------------------------- 🌍 .clear() Remove all items d.clear() 🌍 .copy() Return shallow copy d.copy() 🌍 .fromkeys(iterable, value=None) Create dict from keys dict.fromkeys(['a','b'], 0) 🌍 .get(key[, default]) Return value by key, default None d.get('key', 0) 🌍 .items() Return view of key-value pairs d.items() 🌍 .keys() Return view of keys d.keys() 🌍 .pop(key[, default]) Remove item by key d.pop('key', None) 🌍 .popitem() Remove and return item d.popitem() 🌍 .setdefault(key, default) Get or set value if key missing d.setdefault('key', 0) 🌍 .update([other]) Update dict with another d.update({'a':1}) 🌍 .values() Return view of values d.values() --------------------------------------------------------------------------------------------------------------------------------------------------- 🔒 Set Methods (set & frozenset) --------------------------------------------------------------------------------------------------------------------------------------------------- 🔒 .add(x) Add element s.add(5) 🔒 .clear() Remove all elements s.clear() 🔒 .copy() Return shallow copy s.copy() 🔒 .difference(other) Return set difference s.difference(t) 🔒 .difference_update(other) Remove elements in other s.difference_update(t) 🔒 .discard(x) Remove element if present s.discard(3) 🔒 .intersection(other) Return set intersection s.intersection(t) 🔒 .intersection_update(other) Keep only elements in other s.intersection_update(t) 🔒 .isdisjoint(other) Check if sets have no common elements s.isdisjoint(t) 🔒 .issubset(other) Check if subset s.issubset(t) 🔒 .issuperset(other) Check if superset s.issuperset(t) 🔒 .pop() Remove and return an element s.pop() 🔒 .remove(x) Remove element, raise if missing s.remove(3) 🔒 .symmetric_difference(other) Return elements in either set, not both s.symmetric_difference(t) 🔒 .symmetric_difference_update(other) Update with symmetric difference s.symmetric_difference_update(t) 🔒 .union(other) Return union set s.union(t) 🔒 .update(other) Update set with elements from other s.update(t) --------------------------------------------------------------------------------------------------------------------------------------------------- 📑 Tuple (tuple) --------------------------------------------------------------------------------------------------------------------------------------------------- 📑 .count(x) Count occurrences tpl.count(2) 📑 .index(x[, start, end]) Return index of element tpl.index(3) --------------------------------------------------------------------------------------------------------------------------------------------------- 💠 Bytes & Bytearray Methods --------------------------------------------------------------------------------------------------------------------------------------------------- 💠 .capitalize() Capitalize first char b.capitalize() 💠 .center(width[, fillchar]) Center the bytes object b.center(5, b'*') 💠 .count(sub[, start, end]) Count occurrences b.count(b'a') 💠 .decode(encoding, errors) Decode bytes to str b.decode('utf-8') 💠 .endswith(suffix[, start, end]) Check suffix b.endswith(b'a') 💠 .find(sub[, start, end]) Find substring b.find(b'a') 💠 .index(sub[, start, end]) Find substring, raise if missing b.index(b'a') 💠 .isalnum() Check if alphanumeric bytes b.isalnum() 💠 .isalpha() Check if alphabetic bytes b.isalpha() 💠 .isdigit() Check if digit bytes b.isdigit() 💠 .islower() Check if lowercase bytes b.islower() 💠 .isspace() Check if whitespace bytes b.isspace() 💠 .istitle() Check if titlecase bytes b.istitle() 💠 .isupper() Check if uppercase bytes b.isupper() 💠 .join(iterable) Join bytes iterable b"".join([b'a', b'b']) 💠 .ljust(width[, fillchar]) Left-justify bytes b.ljust(5, b'*') 💠 .lower() Convert bytes to lowercase b.lower() 💠 .lstrip([chars]) Left strip bytes b.lstrip() 💠 .partition(sep) Partition bytes b.partition(b',') 💠 .replace(old, new[, count]) Replace bytes b.replace(b'a', b'b') 💠 .rfind(sub[, start, end]) Find last occurrence b.rfind(b'a') 💠 .rindex(sub[, start, end]) Find last occurrence, raise if missing b.rindex(b'a') 💠 .rjust(width[, fillchar]) Right justify bytes b.rjust(5, b'*') 💠 .rpartition(sep) Partition bytes from right b.rpartition(b',') 💠 .rsplit(sep, maxsplit) Split bytes b.rsplit(b',', 1) 💠 .rstrip([chars]) Right strip bytes b.rstrip() 💠 .split(sep, maxsplit) Split bytes b.split(b',') 💠 .splitlines(keepends) Split lines b.splitlines() 💠 .startswith(prefix[, start, end]) Check prefix b.startswith(b'a') 💠 .strip([chars]) Strip bytes b.strip() 💠 .swapcase() Swap case bytes b.swapcase() 💠 .title() Title case bytes b.title() 💠 .translate(table) Translate bytes b.translate(b.maketrans(b'a', b'b')) 💠 .upper() Convert bytes to uppercase b.upper() 💠 .zfill(width) Zero-fill bytes b.zfill(5) ---------------------------------------------------------------------------------------------------------------------------------------------------