collections.namedtuples() - Dictionary like functionalities with key-value pair. it supports both access from key-value and iteration, which the dictionary method lacks.
__str__ - A python method that returns the user readable string form of an object that can be understood by the end users.
__repr__ - A method returns the string representation of an object.
Instance of Book class - Book("The Odyssey", "Homer")
__repr__ - Book(title='The Odyssey', author='Homer')
__str__ - "The Odyssey" by Homer
The special method .__repr__() returns the official string representation, which is aimed at programmers as they develop and maintain a program. The special method .__str__() returns the informal string representation, a friendlier format for the program’s user[1].
'spades diamonds clubs hearts'.split('e') - ['spad', 's diamonds clubs h', 'arts']
__len__ - A length method
__getitem__ - Method to get a item
random module - Generate random numbers in python [2]
list[slicefrom:]
list [::jumpby]
__setitem__ - Method to set value to a item, For example updating the value of list or adding a value to list.
sorted() - sort the list of items
abs() - Absolute value of a number.
__bool__ - Returns the boolean value of a object
__add__ - Add two vectors
__mul__ - Multiply two vectors
raise - The raise keyword raises a specific exception when a condition is met or the code encounters an error.
SystemExit() - allows us to exit our Python program and provides a return code to the system
reload() - used to reload a previously imported module or loaded module
object - An Object is an instance of a Class
namespaces - A namespace is a system that has a unique name for each and every object in Python. The names are simply all of the global variables, builtin object names and functions defined in the source file. [5]
Variable name in python
Skip the iteration if the variable i is 3, but continue with the next iteration:
Formatting
Date format
"the text is new".find("is") - The find() method finds the first occurrence of the specified value.
replace(str, to_be_replaced) - Replace the "str" with "to_be_replaced"
split() - The split() method splits a string into a list.
append() - The append() method appends an element to the end of the list.
Whenever the file is opened in write mode, all the content which was previously present in the file will be overwritten due to the file pointer having it’s position at the beginning of the file. Whereas in append mode, the file pointer will be at the end of the file and any existing data won’t be overwritten.
Read the file as "r"
with open('Data/portfolio.dat', 'r') as f:
for line in f:
print(line)
f.close()
Built in Python objects
Type of Errors in Python:TypeError
NameError - Raised when a variable is not found in the local or global scope.
ValueError - Raised when a function gets an argument of correct type but improper value.
IndexError - Raised when the index of a sequence is out of range.
KeyError - Raised when a key is not found in a dictionary.
Syntax error - Raised by the parser when a syntax error is encountered.
RuntimeError - Raised when an error does not fall under any other category.
IndentationError - Raised when there is an incorrect indentation.
OverflowError - Raised when the result of an arithmetic operation is too large to be represented.
MemoryError - Raised when an operation runs out of memory.
Solution to avoid memory error - Using the garbage collection.
SystemError - Raised when the interpreter detects internal error.
OSError - Raised when a system operation causes a system-related error.
NotImplementedError - Raised by abstract methods. [4]
UnicodeDecodeError - "UnicodeDecodeError: 'ascii' codec can't decode byte"
ReferenceError - Let's say we have three function A, B and C and A calls B which in turn calls C. If some error occurs in C, same is paseed onto the B, which in turn pushed to A. This type of error is called as reference error.
IOError - IOError in Python is a result of incorrect file name or location.
ArithmeticError - ArithmeticError is simply an error that occurs during numeric calculations.
UnicodeEncodeError - Raised when a Unicode-related error occurs during encoding.
UnicodeTranslateError - Raised when a Unicode-related error occurs during translation.
Error handling Try, Except and finally
Finally is the part of the code that should run regardless of exception
Don't import everthing from the module using from math import *, import only the required methods, this result in poort readability of code and reduce stress on the memory.
if __name__ == '__main__' - __main__ is the name of the environment where top-level code is run. “Top-level code” is the first user-specified Python module that starts running. It’s “top-level” because it imports all other modules that the program needs. Sometimes “top-level code” is called an entry point to the application. [6]
sys.path - This command will list all the paths that are currently added, so let's say we want to import some new module that we have created and the files are present in different location, first we need to add them to the sys.path by running "sys.path.append()", this will make the module files available for importing.
Data Handling:
Tuples - A immutable data structure in python
Dictionaries - A key and value pairs
Class variations
Slots - Saves memory
Dataclasses - Reduce coding
Named Tuples - Immutability
Defaultdict -
Deque - More efficient for que problems
References:
1. https://realpython.com/python-repr-vs-str/
2. https://www.geeksforgeeks.org/python-random-module/
3. https://github.com/dabeaz-course/python-mastery/tree/main
4. https://blog.airbrake.io/blog/python/python-exception-handling-notimplementederror
5. https://www.geeksforgeeks.org/namespaces-and-scope-in-python/
6. https://docs.python.org/3/library/__main__.html#:~:text=__main__%20is%20the,entry%20point%20to%20the%20application.
7.