PythonCheatSheet
PythonCheatSheet
Let's expand the "Advanced Concepts" section and add a new section for "Design Patterns."
○ M
ulti-line:
Python
" ""
This is a multi-line comment.
It can span several lines
and is often used for docstrings.
"""
defgreet(name):
"""
This function greets the person passed in as a parameter.
"""
print(f"Hello,{name}!")
greet("Alice")
● V
ariables:
○ No explicit type declaration. Type is inferred.
○ Python
my_integer_variable =10
my_string_variable ="Python is fun!"
print(my_integer_variable) # Output: 10
print(my_string_variable) # Output: Python is fun!
○ F
loats:Numbers with decimal points.
Python
price =19.99
pi =3.14159
print(f"Price:{price}, Type:{type(price)}")# Output: Price: 19.99, Type: <class 'float'>
○ S
trings:Sequences of characters.
Python
message ="Hello, Python!"
greeting ='Welcome!'
print(f"Message:{message}, Type:{type(message)}")# Output: Message: Hello, Python!,
Type: <class 'str'>
○ B
ooleans:Represent True or False.
Python
is_active =True
has_permission =False
print(f"Is active:{is_active}, Type:{t ype(is_active)}")# Output: Is active: True, Type: <class
'bool'>
○ N
oneType:Represents the absence of a value.
Python
result =None
print(f"Result:{result}, Type:{t ype(result)}") # Output: Result: None, Type: <class
'NoneType'>
2. Operators
● A
rithmetic Operators:
○ + (addition), - (subtraction), * (multiplication), / (division)
Python
a, b =10,3
print(f"10 + 3 ={a + b}")# Output: 10 + 3 = 13
print(f"10 - 3 ={a - b}")# Output: 10 - 3 = 7
print(f"10 * 3 ={a * b}")# Output: 10 * 3 = 30
print(f"10 / 3 ={a / b}")# Output: 10 / 3 = 3.333...
○ %
(modulo - remainder)
Python
print(f"10 % 3 ={1 0%3}" )# Output: 10 % 3 = 1 (10 divided by 3 is 3 with a remainder of 1)
○ * * (exponentiation)
Python
print(f"2 ** 3 ={2 **3} ") # Output: 2 ** 3 = 8 (2 to the power of 3)
● C
omparison Operators:
○ == (equal to), != (not equal to)
Python
print(f"5 == 5:{5
==5} ") # Output: 5 == 5: True
print(f"5 != 10:{5!=10}" )# Output: 5 != 10: True
○ <
(less than), > (greater than)
Python
print(f"5 < 10:{5 <10}") # Output: 5 < 10: True
print(f"10 > 5:{1 0>5} ") # Output: 10 > 5: True
○ <
= (less than or equal to), >= (greater than or equal to)
Python
print(f"5 <= 5:{5
<=5}" ) # Output: 5 <= 5: True
print(f"10 >= 5:{1 0>=5} ") # Output: 10 >= 5: True
● L
ogical Operators:
○ and (logical AND)
Python
print(f"True and False:{T rueandFalse}") # Output: True and False: False
print(f"True and True:{TrueandTrue}" ) # Output: True and True: True
○ o
r (logical OR)
Python
print(f"True or False:{TrueorFalse}") # Output: True or False: True
print(f"False or False:{FalseorFalse}" )# Output: False or False: False
○ n
ot (logical NOT)
Python
print(f"not True:{n
otTrue}") # Output: not True: False
print(f"not False:{n
otFalse}" )# Output: not False: True
● A
ssignment Operators:
○ = (assign)
Python
x =10
print(f"x ={x}")# Output: x = 10
○ +
=, -=, *= etc. (compound assignment)
■ x += 1 is equivalent to x = x + 1
ython
P
count =5
count +=2# Equivalent to: count = count + 2
print(f"count after +=:{count}")# Output: count after +=: 7
v alue =20
value -=5# Equivalent to: value = value - 5
print(f"value after -=:{value}")# Output: value after -=: 15
● M
embership Operators:
○ in: Checks if a value is present in a sequence (string, list, tuple, set, dictionary keys).
Python
my_fruits = ["apple","banana","cherry"]
print(f"'banana' in my_fruits:{'banana'inmy_fruits}") # Output: True
print(f"'grape' in my_fruits:{'grape'inmy_fruits}") # Output: False
print(f"'Py' in 'Python':{'Py'in'Python'}" ) # Output: True
y_dict_keys = {"name":"Alice","age":30}
m
print(f"'name' in my_dict_keys:{'name'inmy_dict_keys}")# Output: True (checks keys)
○ n
ot in: Checks if a value isnotpresent in a sequence.
Python
numbers = [1,2,3]
print(f"5 not in numbers:{5
notinnumbers}")# Output: True
○ A
ccess: my_list[0] (first element), my_list[-1] (last element)
Python
print(f"First element:{my_list[0]}") # Output: First element: 1
print(f"Last element:{my_list[-1] }")# Output: Last element: True
○ S
licing: my_list[1:3] (elements from index 1 up to but not including 3)
Python
print(f"Slice (1 to 3):{my_list[1:3 ] }") # Output: Slice (1 to 3): [2, 3]
print(f"Slice from beginning to 2:{my_list[:3]}")# Output: Slice from beginning to 2: [1, 2, 3]
print(f"Slice from index 2 to end:{my_list[2:]}") # Output: Slice from index 2 to end: [3,
'apple', True]
○ M
ethods: append(), extend(), insert(), remove(), pop(), sort(), reverse(), len()
Python
fruits = ["apple","banana"]
fruits.append("cherry")
print(f"After append:{fruits}") # Output: After append: ['apple', 'banana', 'cherry']
ore_fruits = ["date","elderberry"]
m
fruits.extend(more_fruits)
print(f"After extend:{fruits}")# Output: After extend: ['apple', 'banana', 'cherry', 'date',
'elderberry']
f ruits.insert(1,"grape")
print(f"After insert:{fruits}")# Output: After insert: ['apple', 'grape', 'banana', 'cherry', 'date',
'elderberry']
f ruits.remove("banana")
print(f"After remove:{fruits}") # Output: After remove: ['apple', 'grape', 'cherry', 'date',
'elderberry']
umbers = [3,1,4,1,5,9]
n
numbers.sort()
print(f"After sort:{numbers}")# Output: After sort: [1, 1, 3, 4, 5, 9]
umbers.reverse()
n
print(f"After reverse:{numbers}")# Output: After reverse: [9, 5, 4, 3, 1, 1]
● T
uples (Immutable, Ordered, Indexed):
○ Creation:
Python
my_tuple = (1,2,"banana",False)
print(f"Created tuple:{my_tuple}")# Output: Created tuple: (1, 2, 'banana', False)
○ A
ccess/Slicing: Same as lists
Python
print(f"First element of tuple:{my_tuple[0] }")# Output: First element of tuple: 1
print(f"Tuple slice (1 to 3):{my_tuple[1:3]}") # Output: Tuple slice (1 to 3): (2, 'banana')
○ C
annot modify elements after creation.
Python
my_tuple[0] = 99 # This would raise a TypeError: 'tuple' object does not support item
#
assignment
# print(my_tuple)
● D
ictionaries (Mutable, Unordered, Key-Value Pairs):
○ Creation:
Python
my_dict = {"name":"Bob","age":25,"city":"London"}
print(f"Created dictionary:{my_dict}") # Output: Created dictionary: {'name': 'Bob', 'age': 25,
'city': 'London'}
○ A
ccess:
Python
print(f"Name from dict:{my_dict['name']}")# Output: Name from dict: Bob
○ A
dd/Modify:
Python
my_dict["country"] ="UK"
print(f"After adding 'country':{my_dict}") # Output: After adding 'country': {'name': 'Bob',
'age': 26, 'city': 'London', 'country': 'UK'}
my_dict["age"] =26
print(f"After modifying 'age':{my_dict}") # Output: After modifying 'age': {'name': 'Bob', 'age':
26, 'city': 'London', 'country': 'UK'}
○ M
ethods: keys(), values(), items(), get(), pop()
Python
print(f"Keys:{my_dict.keys()}") # Output: Keys: dict_keys(['name', 'age', 'city', 'country'])
print(f"Values:{my_dict.values()}") # Output: Values: dict_values(['Bob', 26, 'London', 'UK'])
print(f"Items:{my_dict.items()}") # Output: Items: dict_items([('name', 'Bob'), ('age', 26),
('city', 'London'), ('country', 'UK')])
# Using get() to safely access a key (returns None if key not found)
print(f"Get 'city':{my_dict.get('city')}") # Output: Get 'city': London
rint(f"Get 'zip' (default None):{my_dict.get('zip')}")# Output: Get 'zip' (default None): None
p
print(f"Get 'zip' (with default value):{my_dict.get('zip','N/A')}")# Output: Get 'zip' (with
default value): N/A
● S
ets (Mutable, Unordered, Unique Elements):
○ Creation:
Python
my_set = {1,2,3,3,4,2} # Duplicates are automatically removed
print(f"Created set:{my_set}") # Output: Created set: {1, 2, 3, 4} (order may vary)
○ A
dd:
Python
my_set.add(5)
print(f"After adding 5:{my_set}")# Output: After adding 5: {1, 2, 3, 4, 5}
my_set.add(3) # Adding an existing element does nothing
print(f"After adding 3 again:{my_set}") # Output: After adding 3 again: {1, 2, 3, 4, 5}
○ R
emove:
Python
my_set.remove(1)
print(f"After removing 1:{my_set}") # Output: After removing 1: {2, 3, 4, 5}
# my_set.remove(99) # This would raise a KeyError if 99 is not in the set
my_set.discard(99)# discard() does not raise an error if element not found
print(f"After discarding 99:{my_set}")# Output: After discarding 99: {2, 3, 4, 5}
○ S
et operations: union(), intersection(), difference()
Python
set_a = {1,2,3,4}
set_b = {3,4,5,6}
rint(f"Union (A | B):{set_a.union(set_b)}")
p # Output: Union (A | B): {1, 2, 3, 4, 5, 6}
print(f"Intersection (A & B):{set_a.intersection(set_b)}")# Output: Intersection (A & B): {3, 4}
print(f"Difference (A - B):{set_a.difference(set_b)}") # Output: Difference (A - B): {1, 2}
print(f"Symmetric Difference (A ^ B):{set_a.symmetric_difference(set_b)}") # Output:
Symmetric Difference (A ^ B): {1, 2, 5, 6}
# Using range()
print("Using range():")
foriinrange(5
):# 0, 1, 2, 3, 4
print(i)
# Output: 0, 1, 2, 3, 4 (each on a new line)
print("Using range(start, stop, step):")
foriinrange(1 ,10,2) :# 1, 3, 5, 7, 9
print(i)
# Output: 1, 3, 5, 7, 9 (each on a new line)
● w
hile loops (Conditional Iteration):
Python
count =0
whilecount <3:
print(f"Count is{count}")
count +=1
Output:
#
# Count is 0
# Count is 1
# Count is 2
● b
reak and continue:
○ break: Exits the loop immediately.
Python
print("Using break:")
foriinrange(1 0):
ifi ==5:
break# Exit the loop when i is 5
print(i)
Output:
#
# 0
# 1
# 2
# 3
# 4
○ c
ontinue: Skips the rest of the current iteration and moves to the next.
Python
print("Using continue:")
foriinrange(5
):
ifi %2==0:# If i is even
continue # Skip the print statement for even numbers
print(i)
Output:
#
# 1
# 3
5. Functions
● F
unction Definition (def):
Python
defmy_function(parameter1, parameter2=None):
"""Docstring: Explains what the function does.
param1: (Required) A description of parameter1.
param2: (Optional) A description of parameter2 with its default value.
"""
# Function body: code executed when the function is called
print(f"Inside my_function: param1={parameter1}, param2={parameter2}")
returnparameter1 *2
● C
alling a Function:This is how you execute the code defined within a function. You use
the function's name followed by parentheses () containing any required arguments.
Python
# Calling my_function with only the required argument
result1 = my_function(10)
print(f"Result of first call:{result1}")
Output:
#
# Inside my_function: param1=10, param2=None
# Result of first call: 20
● A
rguments:
○ Positional arguments (as shown above)
K
○ eyword arguments (as shown above)
○ Arbitrary positional arguments (*args): Gathers all remaining positional arguments
into a tuple.
Python
deffunc_with_args(*args):
print(f"Args received:{args}")
func_with_args(1,2,"hello",True)
# Output: Args received: (1, 2, 'hello', True)
○ A
rbitrary keyword arguments (**kwargs): Gathers all remaining keyword arguments
into a dictionary.
Python
deffunc_with_kwargs(**kwargs):
print(f"Kwargs received:{kwargs}")
○ C
ombining all argument types:
Python
deffunc_with_all(required_param, *args, default_param="default", **kwargs):
print(f"Required Param:{required_param}")
rint(f"Positional Args (*args):{args}")
p
print(f"Default Param:{default_param}")
print(f"Keyword Args (**kwargs):{kwargs}")
● R
eturn Values:Functions can send data back using the return statement.
Python
defcalculate_area(length, width):
area = length * width
returnarea# Returns the calculated area
r oom_area = calculate_area(5,8)
print(f"The area of the room is:{room_area}square units.")# Output: The area of the room is: 40
square units.
● L
ambda Functions (Anonymous functions):Small, single-expression functions.
○ Python
add =lambdax, y: x + y
print(f"Lambda add(2, 3):{add(2,3)}")# Output: Lambda add(2, 3): 5
6. Input/Output
● I nput from user:name = input("Enter your name: ") (returns a string)
Python
user_name = input("Please enter your name: ")
#
# print(f"Hello, {user_name}!")
# Example interaction:
# Please enter your name: Gini
# Hello, Gini!
● P
rint to console (print()):
○ Basic printing:
Python
print("Hello, World!")# Output: Hello, World!
○ U
sing sep and end arguments:
Python
item_price =150.00
print("Product:","Laptop","Price:", item_price, sep=" | ", end=".\n")
# Output: Product: | Laptop | Price: | 150.0.
print("This is on a new line because of previous 'end'.")
○ O
ld-style % formatting (less common now):
Python
print("My name is %s and I am %d years old."% ("Frank",35))
# Output: My name is Frank and I am 35 years old.
withopen("example.txt","r")asfile:
ontent_after_append = file.read()
c
print("\nContent after append:")
print(content_after_append)
exceptIOErrorase:
print(f"Error handling file:{e}")
# After running this, a file named 'example.txt' will be created/modified in the same directory.
○ M
odes:
■ "r": Read (default)
■ "w": Write (creates new file or truncates existing)
■ "a": Append (adds to end of file)
■ "x": Exclusive creation (fails if file exists)
Python
try:
#
# with open("new_exclusive_file.txt", "x") as file:
# file.write("This file was created exclusively.")
# print("new_exclusive_file.txt created successfully.")
# except FileExistsError:
# print("new_exclusive_file.txt already exists!")
■ " b": Binary mode (e.g., for images, rb, wb)
Python
with open("image.jpg", "rb") as img_file:
#
# binary_data = img_file.read()
# # process binary_data
○ fi
le.readline(): Reads one line at a time.
Python
withopen("example.txt","r")asfile:
first_line = file.readline()
second_line = file.readline()
print(f"First line:{first_line.strip()}")
print(f"Second line:{second_line.strip()}")
Output (after previous writes):
#
# First line: Hello, Python!
# Second line: This is a new line.
○ fi
le.readlines(): Reads all lines into a list of strings.
Python
withopen("example.txt","r")asfile:
all_lines = file.readlines()
print("All lines as a list:")
forlineinall_lines:
print(line.strip())# .strip() removes trailing newline characters
Output (after previous writes):
#
# All lines as a list:
# Hello, Python!
# This is a new line.
# Appending another line.
● W
riting:
○ file.write(string): Writes a string to the file.
Python
# Already shown in the examples for "w" and "a" modes above.
Python
try:
# Code that might raise an exception
num1 =int(input(" Enter a numerator: "))
num2 =int(input(" Enter a denominator: "))
result = num1 / num2
print(f"Result of division:{result}")
exceptZeroDivisionError:
print("Error: Cannot divide by zero!")
exceptValueError:
print("Error: Invalid input. Please enter integers only.")
exceptExceptionase:# Catch any other unexpected exceptions
print(f"An unexpected error occurred:{e}")
else:
# Code to run if no exceptions occurred in the 'try' block
print("Division successful, no errors encountered.")
nally:
fi
# Code that always runs, regardless of exceptions
print("Execution of the division attempt finished.")
● O
bject Instantiation (Creating Instances):This is the act of creating anobject(a
specific instance) from aclassblueprint.
Python
# Creating instances (objects) of the Dog class
my_dog = Dog("Buddy",5)# Calls the __init__ method
your_dog = Dog("Lucy",2)
Output:
#
# A new dog named Buddy has been created!
# A new dog named Lucy has been created!
● A
ccessing Attributes/Methods:
Python
# Accessing instance attributes
print(f"My dog's name:{my_dog.name}") # Output: My dog's name: Buddy
print(f"Your dog's age:{your_dog.age}") # Output: Your dog's age: 2
# Accessing class variables
print(f"Species (from class):{Dog.species}") # Output: Species (from class): Canis
familiaris
print(f"My dog's species (from instance):{my_dog.species}") # Output: My dog's species (from
instance): Canis familiaris
# Calling static methods (can be called via class or instance, but class is common)
print(Dog.describe_dog_breed()) # Output: Dogs are loyal companions.
print(my_dog.describe_dog_breed()) # Output: Dogs are loyal companions.
defretrieve(self):
returnf"{self.name}is retrieving the ball!"
olden = Labrador("Goldie",3,"Golden")
g
print(f"New Labrador:{golden.name}, Age:{golden.age}, Color:{golden.color}")
print(golden.bark()) # Inherited method
print(golden.retrieve()) # New method
Output:
#
# A new dog named Goldie has been created!
# New Labrador: Goldie, Age: 3, Color: Golden
# Goldie says Woof!
# Goldie is retrieving the ball!
classCow:
defmake_sound(self):
return"Moo!"
We need to ensure Dog also has a make_sound method for this example to work fully
#
classNewDog(Dog):# A slightly modified Dog class for this example
defmake_sound(self):
returnself.bark()# Reusing the bark logic
y_pet = Cat()
m
farm_animal = Cow()
my_new_dog = NewDog("Sparky",4)# Instantiate the NewDog
defanimal_sound(animal):
print(animal.make_sound())
● E
ncapsulation:Bundling data (attributes) and methods that operate on the data within a
single unit (class). Access control (e.g., private attributes using __).
Python
classBankAccount:
def__init__(self, balance):
self.__balance = balance# __balance is a "private" attribute (name mangling)
defdeposit(self, amount):
ifamount >0:
self.__balance += amount
print(f"Deposited{amount}. New balance:{self.__balance}")
else:
print("Deposit amount must be positive.")
defwithdraw(self, amount):
if0< amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew{amount}. New balance:{self.__balance}")
else:
print("Invalid withdrawal amount or insufficient funds.")
defget_balance(self):
returnself.__balance
ccount = BankAccount(100)
a
account.deposit(50) # Output: Deposited 50. New balance: 150
account.withdraw(30) # Output: Withdrew 30. New balance: 120
print(f"Current balance:{account.get_balance()}") # Output: Current balance: 120
● D
under Methods (Magic Methods):Special methods identified by double underscores
(__method__) that allow Python classes to interface with built-in functions and operators.
○ __str__(self): Defines the informal string representation of an object, returned by str()
and print(). Should be readable for end-users.
Python
classBook:
def__init__(self, title, author, pages):
s elf.title = title
self.author = author
self.pages = pages
def__str__(self):
returnf'"{self.title}" by{self.author}'
def__repr__(self):
returnf"Book('{self.title}', '{self.author}',{self.pages})"
○ _ _repr__(self): Defines the "official" string representation of an object, returned by
repr() and used in interactive environments (like IDLE/Jupyter). Should be
unambiguous and, if possible, allow recreation of the object.
Python
# (Continued from Book example above)
book_repr =repr(book)
print(book_repr)# Uses __repr__ # Output: Book('The Hitchhiker\'s Guide to the Galaxy',
'Douglas Adams', 193)
# eval(book_repr) would ideally recreate the object if all constructor args are representable
collection = MyCollection([1,2,3,4,5])
print(f"Length of collection:{len(collection)}") # Output: Length of collection: 5
lass Vector:
c
def init(self, x, y):
self.x = x
self.y = y
def add(self, other):
return Vector(self.x + other.x, self.y1 + other.y)
def str(self):2 # For easy printing
return f"Vector({self.x}, {self.y})"
v 1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2 # Calls v1.__add__(v2)
print(f"v1 + v2 = {v3}") # Output: v1 + v2 = Vector(4, 6)
̀ ``
* Many more dunder methods exist for comparison (`__eq__`, `__lt__`), iteration (`__iter__`,
̀ __next__`), attribute access (`__getattr__`, `__setattr__`), callables (`__call__`), etc.
int_val =45
str_val =str(int_val)
print(f"{int_val}as str: '{str_val}', Type:{t ype(str_val)}") # Output: 45 as str: '45', Type: <class 'str'>
oat_val =float("3.14")
fl
print(f"'3.14' as float:{float_val}, Type:{t ype(float_val)}") # Output: '3.14' as float: 3.14, Type: <class
'float'>
z ero =0
empty_string =""
list_val = [1]
print(f"bool(0):{b ool(zero)}") # Output: bool(0): False
print(f"bool(''):{b
ool(empty_string)}") # Output: bool(''): False
print(f"bool([1]):{b ool(list_val)}") # Output: bool([1]): True
● r ange(start, stop, step): Generates a sequence of numbers (used in for loops).
Python
# Already covered in for loops, but here's a direct example:
my_range =range(3,10,2) # Start at 3, stop before 10, step by 2
print(f"Numbers in range(3, 10, 2):{list(my_range)}") # Output: Numbers in range(3, 10, 2): [3, 5, 7,
9]
● a
bs(): Absolute value.
Python
print(f"Absolute value of -5:{a bs(-5) }")# Output: Absolute value of -5: 5
print(f"Absolute value of 5:{abs(5) }") # Output: Absolute value of 5: 5
● e
numerate(): Iterate with an index.
Python
items = ["a","b","c"]
forindex, valueinenumerate(items):
print(f"Index{index}:{value}")
Output:
#
# Index 0: a
# Index 1: b
# Index 2: c
● m
ap(): Apply a function to all items in an iterable.
Python
defsquare(num):
returnnum * num
numbers = [1,2,3,4]
s quared_numbers =list(map(square, numbers))
print(f"Squared numbers (map):{squared_numbers}")# Output: Squared numbers (map): [1, 4, 9,
1 6]
# Often replaced by list comprehensions for readability
● fi
lter(): Filter items from an iterable based on a function.
Python
defis_even(num):
returnnum %2==0
umbers = [1,2,3,4,5,6]
n
even_numbers_filtered =list(fi lter(is_even, numbers))
print(f"Even numbers (filter):{even_numbers_filtered}") # Output: Even numbers (filter): [2, 4, 6]
# Often replaced by list comprehensions for readability
● s orted(): Returns a new sorted list from the items in an iterable.
Python
unsorted_list = [3,1,4,1,5,9,2]
sorted_list =sorted(unsorted_list)
print(f"Sorted list:{sorted_list}")# Output: Sorted list: [1, 1, 2, 3, 4, 5, 9]
● a
ny(), all():
○ any(): Returns True ifanyelement of the iterable is true.
○ all(): Returns True ifallelements of the iterable are true.
ython
P
bool_list1 = [True,False,True]
bool_list2 = [False,False,False]
bool_list3 = [True,True,True]
rint(f"any({bool_list1}):{a
p ny(bool_list1)}") # Output: any([True, False, True]): True
print(f"any({bool_list2}):{a ny(bool_list2)}")# Output: any([False, False, False]): False
print(f"all({bool_list1}):{a
ll(bool_list1)}")# Output: all([True, False, True]): False
print(f"all({bool_list3}):{a
ll(bool_list3)}")# Output: all([True, True, True]): True
11. List, Dictionary, and Set Comprehensions
● L
ist Comprehensions:(Already covered, but good to reiterate here)
Python
squares = [x**2forxinrange(5 )]
print(f"Squares:{squares}") # Output: Squares: [0, 1, 4, 9, 16]
● D
ictionary Comprehensions:
Python
keys = ["a","b","c"]
values = [1,2,3]
my_dict_comp = {k: vfork, vinzip(keys, values)}
print(f"Dict comprehension:{my_dict_comp}")# Output: Dict comprehension: {'a': 1, 'b': 2, 'c': 3}
● S
et Comprehensions:
Python
unique_squares = {x**2forxin[-1,1,2, -2] }# Duplicates are removed automatically
print(f"Set comprehension:{unique_squares}") # Output: Set comprehension: {1, 4} (order may
vary)
● A
liasing imports:import numpy as np
Python
For this to run, you'd typically need to install numpy: pip install numpy
#
# import numpy as np
# arr = np.array([1, 2, 3])
# print(f"Numpy array: {arr}")
s ay_hello()
# Output:
# Something is happening before the function is called.
# Hello!
# Something is happening after the function is called.
● G
enerators (yield):Functions that return an iterator that produces a sequence of results
on demand, instead of building a full list in memory.
Python
defcount_up_to(max_num):
count =1
whilecount <= max_num:
yieldcount# Pauses execution and yields a value
count +=1
y_generator = count_up_to(3)
m
print(f"First yield:{next(my_generator)}") # Output: First yield: 1
print(f"Second yield:{next(my_generator)}")# Output: Second yield: 2
print("Looping through the rest:")
fornuminmy_generator:
print(num)
Output:
#
# Looping through the rest:
# 3
● C
ontext Managers (with statement):Ensures resources are properly acquired and
released (e.g., files, locks). Uses __enter__ and __exit__ methods.
Python
Example (File handling is the most common built-in context manager)
#
# Shown in File Handling section:
# with open("myfile.txt", "w") as f:
# f.write("Hello")
withMyContext()asmc:
print("Inside the context")
raise ValueError("Something went wrong!") # Uncomment to see exception handling
#
# Output:
# Entering the context
# Inside the context
# (If ValueError was uncommented: An exception occurred: Something went wrong!)
# Exiting the context
● I terators:Objects that implement __iter__() and __next__() methods, allowing them to be
iterated over (e.g., in for loops).
Python
classMyRangeIterator:
def__init__(self, limit):
self.limit = limit
self.current =0
def__iter__(self):
returnself
def__next__(self):
ifself.current < self.limit:
self.current +=1
returnself.current
else:
raiseStopIteration
● D
escriptors:Protocol for how attribute access works, allowing customization of attribute
behavior (advanced OOP).
Python
classTen:
def__get__(self, obj, objtype=None):
return10
def__set__(self, obj, value):
print(f"Cannot set 'Ten' directly, trying to set{value}")
# Usually, you'd raise an AttributeError or handle it.
# For demonstration, we'll allow setting but show the message.
# To truly prevent setting, you'd typically raise AttributeError.
obj.__dict__['x'] = value# Sets directly on the instance's dictionary
classA:
x = Ten()# x is now a descriptor
_instance = A()
a
print(f"Accessing a_instance.x (via descriptor):{a_instance.x}")# Output: Accessing a_instance.x
(via descriptor): 10
a_instance.x =20# Calls Ten.__set__
# Output: Cannot set 'Ten' directly, trying to set 20
print(f"Accessing a_instance.x after assignment:{a_instance.x}")# Output: Accessing
a_instance.x after assignment: 20
# Note: If __set__ was not defined, a.x = 20 would create an instance attribute named 'x' that
shadows the descriptor.
● M
etaclasses:Classes that create classes. They allow you to customize class creation.
Python
Very advanced, often used in frameworks.
#
classMyMeta(type):
def__new__(mcs, name, bases, attrs):
print(f"Metaclass: Creating class{name}")
# Add a default attribute to all classes created with this metaclass
attrs['creation_info'] =f"Class{name}created by MyMeta"
returnsuper().__new__(mcs, name, bases, attrs)
classMyClass(metaclass=MyMeta):
pass
● A
synchronous Programming (async/await):For concurrent execution without using
threads, primarily for I/O-bound tasks.
○ async: Defines a coroutine, which is a function that can pause its execution and
resume later.
○ await: Pauses the execution of the current coroutine until the awaited async
operation (like I/O) completes.
Python
importasyncio
importtime
asyncdeffetch_data(delay, data_id):
"""Simulates an asynchronous I/O operation (e.g., network request)."""
print(f"[{time.strftime('%H:%M:%S')}] Start fetching data{data_id}(will take{delay}s)...")
awaitasyncio.sleep(delay)# Pauses this coroutine, allows others to run
print(f"[{time.strftime('%H:%M:%S')}] Finished fetching data{data_id}.")
returnf"Data{data_id}fetched successfully"
asyncdefmain():
"""The main asynchronous function to run."""
print(f"[{time.strftime('%H:%M:%S')}] Starting main program.")
def__init__(self, value):
# This __init__ will be called every time Singleton() is called,
# but the actual instance creation only happens once via __new__.
# So, handle initialization carefully for Singletons.
ifnothasattr(self,'_initialized'):# Prevent re-initialization
s elf.value = value
self._initialized =True
print(f"Singleton initialized with value:{self.value}")
rint(f"s1 is s2:{s1iss2}") # Output: s1 is s2: True (they are the same object)
p
print(f"s1.value:{s1.value}") # Output: s1.value: First Value (if _initialized check is used)
print(f"s2.value:{s2.value}")# Output: s2.value: First Value
Output:
#
# Creating the one and only Singleton instance...
# Singleton initialized with value: First Value
# Singleton initialized with value: Second Value (if _initialized check not used)
# s1 is s2: True
# s1.value: First Value
# s2.value: First Value
● F
actory Method Pattern (Creational):Defines an interface for creating an object, but
lets subclasses decide which class to instantiate.3
Python
classDog:
defspeak(self):
return"Woof!"
classCat:
defspeak(self):
return"Meow!"
classAnimalFactory:
@staticmethod
defcreate_animal(animal_type):
ifanimal_type =="dog":
returnDog()
elifanimal_type =="cat":
returnCat()
else:
raiseValueError("Unknown animal type")
● A
dapter Pattern (Structural):Allows objects with incompatible interfaces to
collaborate.
Python
Existing "legacy" system interface
#
classOldLogger:
deflog_message(self, msg):
print(f"Old Log:{msg}")
● B
uilder Pattern (Creational):Separates the construction of a complex object from its
representation, allowing the same construction process4 to create different
r epresentations.5
Python
classBurger:
def__init__(self):
s elf.buns =None
self.patty =None
self.cheese =None
self.sauces = []
self.vegetables = []
def__str__(self):
return(f"Burger with:{self.buns}buns,{self.patty}patty, "
f"{'cheese'ifself.cheeseelse'no cheese'}, "
f"sauces:{', '.join(self.sauces)ifself.sauceselse'none'}, "
f"veg:{', '.join(self.vegetables)ifself.vegetableselse'none'}")
classBurgerBuilder:
def__init__(self):
self.burger = Burger()
defadd_buns(self, bun_type):
self.burger.buns = bun_type
returnself# Allows chaining
defadd_patty(self, patty_type):
self.burger.patty = patty_type
returnself
defadd_cheese(self):
self.burger.cheese =True
returnself
defadd_sauce(self, sauce_type):
self.burger.sauces.append(sauce_type)
returnself
defadd_vegetable(self, veg_type):
self.burger.vegetables.append(veg_type)
returnself
defbuild(self):
returnself.burger
cheese_burger = (BurgerBuilder()
.add_buns("sesame")
.add_patty("beef")
.add_cheese()
.add_sauce("ketchup")
.add_sauce("mustard")
.build())
print(cheese_burger)
# Output: Burger with: sesame buns, beef patty, cheese, sauces: ketchup, mustard, veg: none
defadd_observer(self, observer):
self._observers.append(observer)
defset_data(self, value):
ifself._data != value:
self._data = value
self._notify_observers()
defget_data(self):
returnself._data
def_notify_observers(self):
forobserverinself._observers:
observer.update()
2. View (Presentation)
#
classTextView:
def__init__(self, model):
s elf._model = model
self._model.add_observer(self)# View observes the Model
defupdate(self):
# React to model changes and update display
print(f"View Updated: Data is now{self._model.get_data()}")
defdisplay(self):
print(f"Current View Display:{self._model.get_data()}")
defincrement_data(self, amount=1) :
urrent_data = self._model.get_data()
c
self._model.set_data(current_data + amount)
defdecrement_data(self, amount=1):
urrent_data = self._model.get_data()
c
self._model.set_data(current_data - amount)
# Initial display
view.display()# Output: Current View Display: 0
controller.increment_data(5)
# Output: View Updated: Data is now 6
controller.decrement_data(2)
# Output: View Updated: Data is now 4
his extended cheat sheet now thoroughly covers dunder methods, more design patterns,
T
and an introduction to architectural patterns, making it even more robust for Python
developers!
ources
S
1.https://github.com/Mendkelokesh12/PW_-Assignments
2.https://www.scribd.com/document/673269950/Python-Programming-19-06-2023
3.https://codebricks.co.nz/python-oop-example-01
4.https://github.com/Akash193119/june
5.https://blog.csdn.net/ak_bingbing/article/details/134936284
6.https://github.com/0nur0duncu/python-files
7.https://github.com/sallehteh2003/Python
8.https://www.owlift.com/blog/submission/what-do-you-mean-by-operator-overloading-2/
9.https://www.datacamp.com/pt/blog/top-python-interview-questions-and-answers
10.https://blog.csdn.net/qq_45150540/article/details/134257875
11.https://github.com/hulinhui/Spiders
12.https://blog.csdn.net/likinguuu/article/details/131253973
13.https://github.com/bazera/ts-design-patterns
14.https://github.com/syurskyi/Python_Topics
15.
http://usawealthnewsdaily.com/stories/how-to-leverage-llms-for-effective-and-scalable-software-
development,522531?
16.https://github.com/code0monkey1/typescript-design-patterns
17.https://anakut.com/en/posts/rust/
18.https://blog.pixelfreestudio.com/how-to-implement-design-patterns-for-maintainable-code/