Python Getting Started
資料來源
- :thumbsup: 為你自己學 PYTHON
- Python @ CodeCademy
- Complete-Python-3-Bootcamp @ GitHub
# 在 REPL 環境下載入某支檔案
$ python -i hello.py
Setup & Installation
PIP
官方文件
- PIP
- Version Specifiers:安裝特定版本的套件
$ pip list # 檢視目前電腦上安裝哪些 python package
$ pip install [package] # 安裝套件
$ pip uninstall [package] # 移除套件
$ pip show [package] # 檢視套件資訊
venv
# 建立 virtual env
$ python -m venv [virtual_environment_name]
$ python -m venv .venv # 建立名為 .venv 的 virtual environment
# 啟動 virtual env
$ source [virtual_environment_name]/bin/activate
# 進入 virtual env 後,使用 deactivate 可以離開
> deactivate
# 把目前專案有安裝的套件寫進 requirement.txt 中
$ pip freeze > requirements.txt
# 安裝 requirement.txt 中列出的套件
$ pip install -r requirements.txt
Poetry
參考:[note] Python Poetry @ PJCHENder
VSCode
Getting Started with Python in VS Code @ Youtube
Data Structure Basic
Variable
a = 3
type(a) # int
String
##
# Index and Slice
##
'tinker'[1:4] # 'ink'
'tinker'[1:4:2] # 'ik'
'tinker'[::-1] # 'reknit
##
# Formatting with the .format() method
##
'Good {}, {} Chen!'.format('morning', 'Mr.') # 'Good morning, Mr. Chen!'
'My favorite brand is {}, {}, and {}!'.format('Apple', 'Samsung', 'Google') # 'My favorite brand is Apple, Samsung, and Google!'
'My favorite brand is {2}, {1}, and {0}!'.format('Apple', 'Samsung', 'Google') # 'My favorite brand is Google, Samsung, and Apple!'
'Repeat after me: {0}! {0}! {0}!'.format('Ho') # 'Repeat after me: Ho! Ho! Ho!'
'Good {time}, {title} {name}!'.format(time='morning', title='Mr.', name='Chen') # 'Good morning, Mr. Chen!'
##
# Float Formatting
##
result = 100/777 # 0.1287001287001287
# Old Way, {value:width.precision f}
print("The result was {:1.3f}".format(result)) # The result was 0.129
# Formatted String Literals(f-strings)
name = 'Aaron'
age = 33
print(f'Hello, my name is {name}, and I\'m {age} years old.')
List
[0]*3 # [0, 0, 0]
my_list = [1, 3, 2]
another_list = [4, 6, 5]
# array concat
whole_list = my_list + another_list
whole_list # [1, 3, 2, 4, 6, 5]
# sort
whole_list.sort()
whole_list # [1, 2, 3, 4, 5, 6]
whole_list.reverse()
whole_list # [6, 5, 4, 3, 2, 1]
Dict
資訊
Mapping Types - Dict @ Python Doc > Built-in Type