Python Coding Essentials
Cheatsheet Content
### Basic Syntax & Data Types - **Variables:** `x = 10`, `name = "Alice"`, `is_true = True` - **Data Types:** - Integers: `int` (e.g., `10`, `-5`) - Floats: `float` (e.g., `3.14`, `-0.5`) - Strings: `str` (e.g., `"hello"`, `'world'`) - Booleans: `bool` (e.g., `True`, `False`) - Lists: `list` (ordered, mutable, `[1, 2, 'a']`) - Tuples: `tuple` (ordered, immutable, `(1, 2, 'a')`) - Dictionaries: `dict` (unordered, mutable key-value pairs, `{'a': 1, 'b': 2}`) - Sets: `set` (unordered, mutable, unique elements, `{1, 2, 3}`) - **Comments:** ```python # This is a single-line comment """ This is a multi-line comment """ ``` - **Printing:** `print("Hello, world!")` - **Input:** `name = input("Enter your name: ")` ### Operators - **Arithmetic:** `+`, `-`, `*`, `/`, `%` (modulo), `**` (exponent), `//` (floor division) - **Comparison:** `==` (equal), `!=` (not equal), ` `, ` =` - **Logical:** `and`, `or`, `not` - **Assignment:** `=`, `+=`, `-=`, `*=` etc. - **Identity:** `is`, `is not` (checks if two variables point to the same object) - **Membership:** `in`, `not in` (checks if an element is in a sequence) ### Control Flow - **If/Elif/Else:** ```python age = 20 if age = 18 and age ### Functions - **Definition:** ```python def greet(name): return f"Hello, {name}!" message = greet("Alice") print(message) # Output: Hello, Alice! ``` - **Default Arguments:** ```python def power(base, exp=2): return base ** exp print(power(3)) # Output: 9 print(power(2, 3)) # Output: 8 ``` - **Arbitrary Arguments:** - `*args` (non-keyword arguments): ```python def sum_all(*numbers): return sum(numbers) print(sum_all(1, 2, 3)) # Output: 6 ``` - `**kwargs` (keyword arguments): ```python def display_info(**info): for key, value in info.items(): print(f"{key}: {value}") display_info(name="Bob", age=30) ``` - **Lambda Functions (Anonymous Functions):** ```python add = lambda x, y: x + y print(add(5, 3)) # Output: 8 ``` ### Common Data Structures Operations #### Lists - **Create:** `my_list = [1, 2, 3]` - **Access:** `my_list[0]` (first element), `my_list[-1]` (last element) - **Slice:** `my_list[1:3]` (elements at index 1 and 2) - **Add:** `my_list.append(4)`, `my_list.insert(1, 5)` - **Remove:** `my_list.remove(2)`, `my_list.pop()` (removes last), `del my_list[0]` - **Length:** `len(my_list)` - **Sort:** `my_list.sort()`, `sorted_list = sorted(my_list)` #### Dictionaries - **Create:** `my_dict = {'name': 'Alice', 'age': 25}` - **Access:** `my_dict['name']`, `my_dict.get('city', 'Unknown')` - **Add/Update:** `my_dict['city'] = 'New York'` - **Remove:** `del my_dict['age']`, `my_dict.pop('name')` - **Keys/Values/Items:** `my_dict.keys()`, `my_dict.values()`, `my_dict.items()` #### Strings - **Concatenate:** `s1 + s2` - **Format:** `f"Name: {name}, Age: {age}"`, `"Name: {}, Age: {}".format(name, age)` - **Methods:** `s.upper()`, `s.lower()`, `s.strip()`, `s.split(' ')`, `s.replace('old', 'new')` ### Error Handling ```python try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") except TypeError as e: print(f"Type error: {e}") else: print("Division successful.") finally: print("Execution finished.") ``` ### File I/O - **Reading a file:** ```python with open("my_file.txt", "r") as f: content = f.read() # Reads entire file # line = f.readline() # Reads one line # lines = f.readlines() # Reads all lines into a list print(content) ``` - **Writing to a file:** ```python with open("output.txt", "w") as f: # "a" for append f.write("Hello from Python!\n") f.write("This is a new line.") ``` ### Classes & Objects (OOP) ```python class Dog: # Class attribute species = "Canis familiaris" def __init__(self, name, age): # Instance attributes self.name = name self.age = age def bark(self): return f"{self.name} says Woof!" def get_age(self): return self.age * 7 # Dog years # Create objects (instances) my_dog = Dog("Buddy", 3) your_dog = Dog("Lucy", 5) print(my_dog.name) # Output: Buddy print(my_dog.species) # Output: Canis familiaris print(my_dog.bark()) # Output: Buddy says Woof! print(your_dog.get_age()) # Output: 35 ``` ### Modules & Packages - **Importing:** ```python import math print(math.sqrt(16)) # Output: 4.0 from datetime import datetime print(datetime.now()) import random as rnd print(rnd.randint(1, 10)) ``` - **Creating a module:** Save functions/classes in a `.py` file (e.g., `my_module.py`). - **Creating a package:** A directory containing an `__init__.py` file and other modules. ### List Comprehensions - **Basic:** `squares = [x**2 for x in range(10)] # [0, 1, 4, ..., 81]` - **With condition:** `evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]` - **Nested:** `matrix = [[j for j in range(3)] for i in range(3)] # [[0, 1, 2], [0, 1, 2], [0, 1, 2]]` ### Generators & Decorators #### Generators - Functions that return an iterator, producing items one at a time using `yield`. ```python def count_up_to(max_val): count = 1 while count