Learning Python
Python
Install Python + pyenv + virtualenv
- Basic syntax and data types: Start by learning the basic syntax of Python, such as how to define variables, use control structures (like if/else statements and loops), and work with basic data types like strings, integers, and floats.
- Functions and modules: Learn how to define and call functions in Python, and how to work with modules to organize your code and reuse functionality.
- Object-oriented programming: Python is an object-oriented language, so it’s important to understand the basics of classes and objects, as well as inheritance and polymorphism.
- File I/O and exception handling: Learn how to work with files in Python, including reading from and writing to files, and how to handle errors and exceptions in your code.
- Python libraries and frameworks: Once you have a good understanding of the core concepts of Python, start exploring some of the popular Python libraries and frameworks, such as NumPy, Pandas, Django, and Flask, that can help you solve specific problems and build applications.
Installation
Pyenv - Quản lý phiên bản python Virtualenv: Hỗ trợ tạo các môi trường ảo, các thư viện của project sẽ được cài đặt cô lập trong môi trường ảo này.
pyenv virtualenv 3.10.7 xxx
pyenv local xxx
Basic
print(r'C:\some\name')-rfor raw- Lists ~ Array. Dict ~ Hash
- Strings are immutable, lists are a mutable type.
print(a, end=','). Useendkeyword to avoid the newline after the output.range(5),list(range(0, 10, 3))elsecó thể được dùng với vòngfor, mang nghĩa nhưtrycatch, thực hiện nếu hết không có exception nào/ break nào xuất hiện.passđược dùng trong các class/method mà chưa muốn implement, tránh lỗi syntax.match A: case, tương tự vớicase - whentrong Ruby*args- 1 lists các tham số.**kwargs- Một dict- Positional args: Quan trọng vị trí, thứ tự đầu vào. Thường sẽ truyền vào 2 object. (vd:
add(2, 3)). Keyword args: Truyền vào dạng dict nên k cần quan tâm thứ tự đầu vào. /and*in arguments:def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):/: Params truyền vào TRƯỚC/phải là positional args.*Params truyền vào SAU*phải là keyword arguments.- Params ở giữa 2 dấu này có thể là pos hoặc là kwd args.
lambdadùng để define 1 small anonymous function.zip:list(zip(*matrix))- Tuples: ordered, immutable collection of values. Defined using
()and can contain any combination of data types, include other tuples. - Set: unordered collection with no duplicate elements.
- Dict: Tương tự như Hash bên Ruby.
Modules
https://docs.python.org/3/tutorial/
- Import dựa vào tên file.
import fibo as fib
from fibo import fib as finbonacci
from fibo import fib, fib2
from fibo import *-
Khi 1 modules được import, Python sẽ tìm chúng trong:
sys.builtin_module_names- Module builtinsys.path:- Location hiện tại.
- PYTHONPATH
- site-packages dir
-
Python cache compiled modules to
.pycfiles. Check tự động dựa vào modified time của file module.
Input & Output
Formated string literals
f'orF'for string literals. Eg:f'Results of the {year} {event}'str.format()do the same:'{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)str(x)orrepr(s)convert object to string. Same for{animal!r}- print debugging:
print(f'Debugging {bugs=} {count=} {area=}') str.rjust()- right-justifies.str.ljust()andstr.center().str.zill(x)
Reading and Writing files
f = open('workfile', 'w', encoding="utf-8")f.read(),f.readline(),for line in fjson.dump(x),json.load(f)
Errors and Exceptions
- Handle exception bassed
try .. except exceptclause were reversed - same asrescueon Rails.- Can used with
else- Code will be executed if no exceptions are raised. finally- Code is executed after all.- Use
withto open file. So file will be ensured to cleaned. - Use class
ExceptionGroupto group exeptions
Classes
localvariables: inside function.global: outside of any function.nonlocalused when you have nested functions and you want to modify a variable defined in an outer function.data attributesandmethods- class variables will be defined outside class function. CAREFULL when use this, cause they will be shared between objects.
- Kế thừa:
class DerivedClassName(BaseClassName): - Đa kế thừa:
class DerivedClassName(Base1, Base2, Base3):Các methods được kế thừa theo thứ tự 1, 2, 3 - Private không tồn tại trong Python. Có 1 convention là named prefix bằng
_để chỉ non-public part. Dev khác cần cẩn thận khi sử dụng/modify các biến này. - Sử dụng
@dataclassđể definestructgiống bên Ruby - Bản chất của các vòng
forthực ra là dùng statementiter()trên container object. Function này có 1 function nhỏ hơn là__next()__để access element trong container object. Khi hết vòng lặp thì nó dùngStopIteration - Generation là 1 loại iteration đặc biệt, generate values on the fly chứ không lưu nó trong memory. Sử dụng
yieldđể thao tác với values, trả về giá trị tiếp theo ở vòng lặp tiếp.
Standard Library
os: Interacting with OS:getcwd,chdir,system(run command), … Use moduleshutilfor higher level interface.glob- making file lists from directorysys:- Arguments
sys.argv. We can useargparsemodule - Error output redirection and program termination:
stderr,stdin,stdout
- Arguments
re: String pattern matching:finall,sub,replace, …math,random,statistics- Internet Access:
urllib.request,smtplib, … datetime- today, date, days, strftime, …zlib- Data Compression.zlib,gzip,bz2, … Supportcompress,decompresstimeit: Performance Measurement.doctest,unittest- Quality control - Validate doc embedded tests- Output formating:
reprlib,pprint,textwrap,locale - Templating: Create template, and pass args to render string
- Binary Data Record Layouts: use
structmodule with methodspackandunpack - Multi-threading: Use
threadingmodule - Logging:
loggingwith debug, info, warning, error, critical - Weak references: use
weakrefto tracking objects without creating a reference. - Tools for Working with Lists:
array,collections,bisect,heapq - Decimal Floating Point Arithmetic:
decimal. - Sử dụng cho các application liên quan tới tính toán tiền.
Questions
- Tips & Tricks when debugging with Python. (binding, find source location, methods to list object type, method names, …)