Hi 大家好,
今天要開始介紹基礎語法中的函數進階篇之續集,那我們開始吧!
Q: 什麼是模組?
A: 我們可以將一個Python程式依照功能進行分類成為多個檔案,分類後的程式檔案可以視為模組
。
模組的檔案名稱是檔案名稱
加上.py
作為副檔名。模組可以包含變數、函數、類別,甚至是可執行的代碼。主要目的重組程式碼
,增加程式碼可讀性
、重用性
和維護性
。
import math
print(math.pi)
PS D:\Project\practice> python hi.py
3.141592653589793
PS D:\Project\practice>
import os
print(os.getenv("LANG"))
PS D:\Project\practice> python hi.py
en_US.UTF-8
PS D:\Project\practice>
from datetime import date
today = date.today()
print(today)
PS D:\Project\practice> python hi.py
2024-08-16
PS D:\Project\practice>
pip install requests
PS D:\Project\practice> python -m venv .venv
PS D:\Project\practice> cd .\.venv\Scripts\
PS D:\Project\practice\.venv\Scripts> .\Activate.ps1
(.venv) PS D:\Project\practice\.venv\Scripts> pip install requests
Collecting requests
Using cached requests-2.32.3-py3-none-any.whl.metadata (4.6 kB)
Collecting charset-normalizer<4,>=2 (from requests)
Using cached charset_normalizer-3.3.2-cp312-cp312-win_amd64.whl.metadata (34 kB)
Collecting idna<4,>=2.5 (from requests)
Using cached idna-3.7-py3-none-any.whl.metadata (9.9 kB)
Collecting urllib3<3,>=1.21.1 (from requests)
Using cached urllib3-2.2.2-py3-none-any.whl.metadata (6.4 kB)
Collecting certifi>=2017.4.17 (from requests)
Using cached certifi-2024.7.4-py3-none-any.whl.metadata (2.2 kB)
Using cached requests-2.32.3-py3-none-any.whl (64 kB)
Using cached certifi-2024.7.4-py3-none-any.whl (162 kB)
Using cached charset_normalizer-3.3.2-cp312-cp312-win_amd64.whl (100 kB)
Using cached idna-3.7-py3-none-any.whl (66 kB)
Using cached urllib3-2.2.2-py3-none-any.whl (121 kB)
Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests
Successfully installed certifi-2024.7.4 charset-normalizer-3.3.2 idna-3.7 requests-2.32.3 urllib3-2.2.2
[notice] A new release of pip is available: 24.0 -> 24.2
[notice] To update, run: python.exe -m pip install --upgrade pip
(.venv) PS D:\Project\practice\.venv\Scripts> cd ..
(.venv) PS D:\Project\practice\.venv> cd ..
(.venv) PS D:\Project\practice> python hi.py
200
{'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto'}
(.venv) PS D:\Project\practice>
# hello.py
def add(a, b):
return a + b
def hello():
pass
xyz = "9999"
# 如果是單獨執行 __main__
# 是內建變數 __name__
print(__name__)
if __name__ == "__main__":
if add(1, 2) == 3:
print("ok")
else:
print("ng")
直接印出hello.py,會執行if __name__ == "__main__":
判斷式內的結果
(.venv) PS D:\Project\practice> python hello.py
__main__
ok
(.venv) PS D:\Project\practice>
在hi.py中引用hello模組內的變數、函數等
# hi.py
from hello import add, xyz
print(__name__)
print(add(1, 2))
print(xyz)
(.venv) PS D:\Project\practice> python hi.py
hello
__main__
3
9999
(.venv) PS D:\Project\practice>
那今天就介紹到這裡,我們明天見~