跳至主要内容

Python Getting Started

資料來源
# 在 REPL 環境下載入某支檔案
$ python -i hello.py

Setup & Installation

PIP

官方文件
$ 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]

Operators

Comparisons Operators

1 < 2 < 3  # True
1 < 2 and 2 < 3 # True
1 == 1 or 2 == 2 # True
not ( 1 == 1 ) # False
not ( 400 > 5000 ) # True

Useful Operators

range(start, stop, step)

# 0, 1, 2
for i in range(3):
print(i)

# 3, 4
for i in range(3,5):
print(i)

# 1,3,5
for i in range(1,6,2):
print(i)

# [0, 2, 4]
list(range(0, 5, 2))

enumerator

把 string 變成 tuple

word = 'abc'

# 0: a
# 1: b
# 2: c
for idx, value in enumerate(word):
print(f'{idx}: {value}')

zip

把多個 list 組成一個 tuple

name = ['Aaron', 'John', 'Mary']
age = [12, 13, 14]
height = [170, 180, 160]

# Aaron is 12 years old with 170 cm
# John is 13 years old with 180 cm
# Mary is 14 years old with 160 cm
for name, age, height in zip(name, age, height):
print(f'{name} is {age} years old with {height} cm')

# <zip object at 0x1023a1300>
zip(name, age, height)

# [('Aaron', 12, 170), ('John', 13, 180), ('Mary', 14, 160)]
list(zip(name, age, height))

in

1 in [1, 2, 3]  # True

'a' in 'abc' # True
'a' in [1, 2, 3] # False

user = {
"name": "John",
"age": 30,
"city": "New York"
}
'name' in user # True
'John' in user.values()

Statements

Conditional Statements

state = 'active'

if state == 'active':
print('The state is active')
elif state == 'inactive':
print('The state is inactive')
else:
print('The state is unknown')

For Loops

Iterate a list

brands = ['Ford', 'BMW', 'Volvo']
for brand in brands:
print(brand)

Combine with conditional statement:

brands = ['Ford', 'BMW', 'Volvo']
for brand in brands:
if brand == 'Volvo':
print(brand + ' - I like it!')
else:
print(brand + ' - I don\'t like it!')

Iterate a string

str = 'Hello World'
for letter in str:
print(letter)

Iterate a tuple

for t in (1, 2, 3):
print(t)

Tuple Unpacking

my_list = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]

for a, b in my_list:
print(a + b)

Iterate an dictionary

user = {
"name": "John",
"age": 30,
"city": "New York"
}

for key in user:
print(f'key: {key}')
print(f'value: {user[key]}')

for key, value in user.items():
print(f'key: {key}')
print(f'value: {value}')

for value in user.values():
print(value)

While Loops

x = 0
while x < 5:
# x = x + 1
x += 1
print(f'The current value of x is {x}')
# could combine with "else"
else:
print('X IS NOT LESS THAN 5')

Basic I/O

Read and Write files

  • mode='r': read only
  • mode='w': write only (will overwrite existing files or create new)
  • mode='a': append only
  • mode='r+': read and write
  • mode='w+': write and read (overwrite existing files or create new)
myfile = open('myfile.txt')
myfile.read()
myfile.seek(0) # reset cursor
myfile.readlines() # returns a list of lines
myfile.close() # close file

# 不用怕忘記 close 的寫法
# create or overwrite a file
with open('myfile.txt', mode="w") as my_new_file:
contents = my_new_file.write(
'this is a text file\nthis is the second line\nthis is the third line')

# read file
with open('myfile.txt', mode='r') as f:
contents = f.read()
print(contents)

# append file
with open('myfile.txt', mode='a') as f:
f.write('\nthis is the fourth line')

with open('myfile.txt', mode='r') as f:
contents = f.read()
print(contents)

Modules and Packages

定義 Modules 和 Packages

  • Module 指的就是 .py 「檔案」,在 Python 中不需定義要 export 哪些變數,可以自由 import
  • Package 則是一個包含許多 modules 的「資料夾」,要變成 package,只需要在資料夾中加上 __init__.py 的檔案
  • 一個 Package 中還可以有 sub package,只要在該資料夾中同樣加上 __init__.py 的即可。

舉例來說,我們的資料結構如下:

.
├── main_package
│ ├── __init__.py
│ ├── main_script.py # 裡面有定義 report_main()
│ └── sub_package
│ ├── __init__.py
│ └── sub_script.py # 裡面有定義 report_sub_script()
├── my_module.py # 裡面有定義 my_function()
└── my_program.py

如果想要在 my_program 中使用 my_modulemain_packagesub_package 中的方法,只需要這樣 import 即可:

# module 會是 folder name
# package 則是 file name

# from <module> import <method>
from my_module import my_function

# from <package> import <module>
from main_package import main_script

# from <package>.<sub-package> import <module>
from main_package.sub_package import sub_script

my_function()
main_script.report_main()
sub_script.report_sub_script()
判斷是不是直接被執行的程式

如果要判斷某個檔案是不是直接被執行,而不是透過 import 的方式被載入後才執行,可以使用 __name__ == __main__,當這個檔案是直接被執行時,會得到 true

匯入 Packages

在 Python 中要匯入套件可以使用:

# import <module>
# 如果會使用到同一個 package 中的許多不同項目,並且覺得沿用這個 module name 當作 prefix 會比較簡潔時
import math
math.sqrt(4)

# from <module> import <method>
from math import pi, sqrt
sqrt(4)

# import <package>.<module>
import my_package.module1
my_package.module1.foo()

如果有需要的話,也可以使用 as (alias)來替import 的 module 改名字:

import numpy as np
from matplotlib.pyplot import plot as plt

np.array([1, 2, 3])
plt([1, 2, 3], [4, 5, 6])

明確定義其他人 import module 的方式

因為 module 中的所有變數、方法都可以被 import,所以如果我們希望明確定義哪些是「希望」開放給其他人使用的 module 時,可以搭配 as 定義在 __init__.py 中。例如:

# fastapi/__init__.py

"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""

__version__ = "0.111.0"

from starlette import status as status

# 其他人在使用時,可以不用寫 "from fastapi import applications"
# 而是寫 "from fastapi import FastAPI"
# from <module> import <method>
from .applications import FastAPI as FastAPI
# ...

Functions

lambda

透過 lambda 可以:

  • 把函式指派給某個變數
  • 建立出匿名函式
# lambda [函式參數]: 函式內容(不需要特別加 return)
add = lambda x, y: x + y
result = add(2, 3) # 5

# 一樣可以幫參數帶入預設值
add = lambda x, y=3: x + y
result = add(2) # 5

lambda 特別適合用在一次性的函式,如此就不需要特別幫這個函式命名。例如:

employees = [
{"name": "Alice", "salary": 70000},
{"name": "Bob", "salary": 50000},
{"name": "Charlie", "salary": 120000},
]

# Sorting employees by salary using a lambda function
sorted_employees = sorted(employees, key=lambda x: x["salary"])

default values 要留意的地方

在 Python 中,要留意 default value 會被保存在 function 中,如果我們在 function 中 mutate 了 default value,則這個 function 在下一次呼叫時,會用的是新的、被改變多的 default value:

def mutate_default(my_list: list = []):
my_list.append(1)
return my_list

# my_list 的 default value 會被保存在 function 中,不會每次在 function 呼叫時就重新建立新的
mutate_default() # [1]
mutate_default() # [1, 1]
mutate_default() # [1, 1, 1]

留言