Quirks & Tricks
Hey! Here is a compiled breakdown of the highly specific examples, custom exercises, and syntax nuances
1. String Quirks & Tricky Indexing Margins
- Slicing All the Way to the End: Instead of using the standard clean shorthand
str1[1:], we explicitly documented passing thelen()function as the upper bound parameter to guarantee hitting the absolute end of a string:print(str1[1:len(str)]). - Negative-to-Positive Slices: A specific logic pattern used to isolate a suffix from a negative index relative to the total length:
str[-1:len(str)]andprint(marks[-3:-1]). - The "Forever" Mutation Pattern: To remember that string methods return new strings rather than changing them in place, we log this exact assignment pattern to lock it in:
str = str.capitalize() # to capitalize forever. - Counting Manual Spaces: Watch out for leading or trailing whitespace when evaluating string metrics. For example, a targeted string with an intentional leading space changes the expected element count:
python str2 = " this is my second lecture" # Leading space counts! len2 = len(str2) # Evaluates to 26 instead of 25
2. Granular Data Structures & Collections
- The Single-Element Tuple Trap: Dropping a single item inside parentheses makes it a regular primitive unless you include a trailing comma:
python tup = (1,) # Comma is mandatory to maintain type integrity! - Storing Floats and Ints Together in Sets: Sets enforce uniqueness and typically compress duplicates. To store both an integer and its exact floating-point version without triggering a deletion, package them inside tuples:
python values = { ("float", 9.0), ("int", 9) } - Multi-Value Dictionary Thesaurus: A custom mapping approach where a single lookup key points directly to a nested list containing multiple definitions or facts:
python dict1 = { "table" : ["a piece of furniture", "list of facts and figures"], "cat": "a small animal" }
3. Custom File I/O Logic & Text Processing
- Manual CSV String Parsing (No
.split()): Before jumping into built-in string splitting functions, we built a character-by-character iteration loop that catches commas, isolates number buffers, type-casts them on the fly, and flushes the buffer cleanly:python num = "" for i in range(len(data)): if(data[i] == ","): print(int(num)) num = "" else: num += data[i] - Finding the Exact Line Number: Instead of just checking if a word exists, this custom loop sequentially reads a file line-by-line and returns the exact horizontal line index where the substring appears:
python def check_line(): word = "learning" data = True line_no = 1 with open("practice.txt", "r") as f: while data: data = f.readline() if word in data: print(line_no) return line_no += 1 return -1 - The Overwrite Rule (
r+vsw+): Opening a file inr+mode lets you overwrite characters starting exactly from index zero without automatically wiping the rest of the existing downstream text (no automatic truncation).
4. OOP Architecture, Private Attributes & State Shifting
-
Name Mangling and Private Safeguards: Using a double underscore (
__) makes attributes and methods private, triggering error handles if accessed from the outside, but they remain open to internal methods: ```python class Account: def init(self, account_number, account_password): self.account_number = account_number self.__account_password = account_password # Private attributedef reset_password(self): print(self.__account_password) # Perfectly safe inside the class block* **Targeted Property and Instance Deletion:** You can use the `del` keyword to strip specific properties off a live object, or completely dissolve the object instance entirely:python del s1.name # Wipe out an individual property del s1 # Liquidate the whole object reference from memory* **3 Ways to Mutate a Class Variable:** When modifying a shared class state variable (e.g., `name = "anonymous"`), we documented three clear approaches to make the change permanent across instances:pythonStrategy A: Directly targeting the global class blueprint
Person.name = new_name
Strategy B: Dynamic query via instance class dunder
self.class.name = new_name
Strategy C: Explicit Classmethod Decorator mapping
@classmethod def change_name(cls, name): cls.name = name ```
5. Dunder Magic & Object Comparison
- Custom Math Vectors (
__sub__): Overloading operators lets us subtract custom complex object numbers cleanly using double-underscore methods: ```python class complex: def init(self, real, imag): self.real = real self.imag = imagdef __sub__(self, other): newreal = self.real - other.real newimag = self.imag - other.imag return complex(newreal, newimag)* **Comparing Custom Objects (`__gt__`):** We can make instances directly comparable based on internal numeric values (like evaluating which order is more expensive):python class Order: def init(self, item, price): self.item = item self.price = pricedef __gt__(self, other): return self.price > other.price```
6. Personal Coding Mnemonics
- Syntax: Rules rightway / Right way of writing a code.
- Indentation: Right space.
- Concatenation: Attached strings.
- Truncating: Cleans previous data and starts the file fresh for writing.