Skip to content

Instantly share code, notes, and snippets.

@huynhbaoan
Created March 13, 2025 08:04
Show Gist options
  • Save huynhbaoan/f828e35cbdd4c7f81ca0c88836faa29b to your computer and use it in GitHub Desktop.
Save huynhbaoan/f828e35cbdd4c7f81ca0c88836faa29b to your computer and use it in GitHub Desktop.
Python memory
1. Basic Syntax
• Comments:
Use # for single-line comments and triple quotes ("""...""" or '''...''') for multi-line strings or docstrings.
# This is a single-line comment
"""
This is a multi-line comment or docstring.
Useful for module or function documentation.
"""
2. Data Types & Variables
• Numbers: Integers, floats, and complex numbers.
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex number
• Strings:
Use single ('...') or double ("...") quotes.
s = "Hello, Python!"
s2 = 'Single quotes also work'
print(s + " " + s2) # String concatenation
• Booleans:
True and False.
flag = True
if flag:
print("Flag is True")
• Type Conversion:
Convert between types using functions like int(), float(), str(), etc.
num_str = "123"
num = int(num_str)
3. Operators
• Arithmetic Operators:
+, -, *, /, // (floor division), % (modulo), ** (exponentiation)
x = 7
y = 3
print(x + y, x - y, x * y, x / y, x // y, x % y, x ** y)
• Comparison Operators:
==, !=, <, >, <=, >=
print(x == y, x != y, x > y)
• Logical Operators:
and, or, not
print(True and False, True or False, not True)
• Membership Operators:
in, not in
lst = [1, 2, 3]
print(2 in lst, 4 not in lst)
• Identity Operators:
is, is not
a = [1, 2]
b = a
c = [1, 2]
print(a is b, a is c)
4. Control Structures
Conditionals
x = 10
if x < 0:
print("Negative")
elif x == 0:
print("Zero")
else:
print("Positive")
Loops
• For Loop:
# Iterating over a range
for i in range(5):
print(i)
# Iterating over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
• While Loop:
count = 0
while count < 5:
print(count)
count += 1 # Same as count = count + 1
• Loop Control:
Use break to exit and continue to skip an iteration.
for i in range(10):
if i == 5:
break
if i % 2 == 0:
continue
print(i)
5. Functions
• Defining Functions:
def add(a, b):
"""Returns the sum of a and b."""
return a + b
print(add(3, 4))
• Default Arguments:
def greet(name, msg="Hello"):
return f"{msg}, {name}!"
print(greet("Alice"))
print(greet("Bob", "Hi"))
• Variable-Length Arguments:
def func(*args, **kwargs):
print("Positional:", args)
print("Keyword:", kwargs)
func(1, 2, 3, key1="value1", key2="value2")
• Lambda Functions:
For short, anonymous functions.
square = lambda x: x * x
print(square(5))
6. Data Structures
Lists
• Creating and Accessing:
numbers = [1, 2, 3, 4, 5]
print(numbers[0], numbers[-1])
• List Operations:
numbers.append(6) # Append to the list
numbers.extend([7, 8]) # Extend list with another list
numbers.insert(0, 0) # Insert at a specific index
numbers.remove(3) # Remove first occurrence of value 3
popped = numbers.pop() # Remove and return the last item
Tuples
• Immutable Sequences:
point = (10, 20)
x, y = point # Tuple unpacking
Sets
• Unique Elements:
s = {1, 2, 3, 2}
s.add(4)
print(s)
Dictionaries
• Key-Value Pairs:
person = {"name": "Alice", "age": 30}
print(person["name"])
person["age"] = 31 # Update value
for key, value in person.items():
print(key, value)
7. List Comprehensions & Generator Expressions
• List Comprehensions:
squares = [x * x for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
• Generator Expressions:
Similar to list comprehensions but use parentheses for lazy evaluation.
squares_gen = (x * x for x in range(10))
for sq in squares_gen:
print(sq)
8. Exception Handling
• Try/Except Blocks:
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Error:", e)
finally:
print("Cleanup can go here.")
• Raising Exceptions:
def divide(a, b):
if b == 0:
raise ValueError("b cannot be zero!")
return a / b
9. File I/O
• Reading a File:
with open("example.txt", "r") as file:
content = file.read()
print(content)
• Writing to a File:
with open("output.txt", "w") as file:
file.write("Hello, File I/O!")
10. Classes and Object-Oriented Programming
• Defining a Class:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}."
person = Person("Alice", 30)
print(person.greet())
• Inheritance:
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def greet(self):
return f"{super().greet()} I am a student with ID {self.student_id}."
student = Student("Bob", 22, "S12345")
print(student.greet())
11. Modules and Imports
• Importing Modules:
import math
print(math.sqrt(16))
# Importing specific functions
from math import ceil
print(ceil(4.2))
• Using Aliases:
import numpy as np # Common alias for numpy
a = np.array([1, 2, 3])
print(a)
12. Miscellaneous
• String Formatting:
Use f-strings (Python 3.6+) for concise formatting.
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
• Docstrings:
Document your functions and classes.
def add(a, b):
"""
Returns the sum of a and b.
:param a: First number
:param b: Second number
:return: Sum of a and b
"""
return a + b
• Useful Built-in Functions:
Functions like len(), range(), enumerate(), zip(), map(), filter(), sorted(), and reversed() are frequently useful.
lst = [10, 20, 30]
for index, value in enumerate(lst):
print(index, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment