Python Module¶

資訊之芽 梁安哲 2023/04/16

Outline¶

  • Introduction
  • Syntax
  • Your Module
  • Built-in Modules
  • External Modules
  • Additional Information

Introduction¶

What is Module?¶

Simple Answer¶

Benefits¶

  • Module 是別人寫的
    • 不用重新造輪子
  • Module 是自己寫的
    • 不用一個程式檔寫完一整個專案(雖然理論上可以
    • 把程式檔案大小控制在合理的範圍(如同函式之於單個.py檔)
    • 常用的東西(變數、函式、類別)只需要寫一次

Example¶

去年的大作業:

把不同功能的程式碼放在不同檔案裡

Syntax¶

Basic¶

In [14]:
import math
print(math.log10(2))
0.3010299956639812

With Alias¶

In [15]:
import numpy as np
matrix = [[2,3] , [5,7]]
print(np.linalg.inv(np.array(matrix)))
[[-7.  3.]
 [ 5. -2.]]
In [16]:
# 常見別名(第二階段課程)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# import torch.nn as nn

Import specific attributes¶

可個別引入:變數、函式、類別

In [17]:
from random import randint
print(randint(0 , 100))
97
In [18]:
## NOT recommended
from math import *

Error¶

In [19]:
import NeverGonnaGiveYouUp
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[19], line 1
----> 1 import NeverGonnaGiveYouUp

ModuleNotFoundError: No module named 'NeverGonnaGiveYouUp'

Practice¶

使用1000個隨機小數座標估計圓周率$\pi$,利用random.random()生成在$\left[0,1\right)$的隨機小數。

Hint¶

$$ A(Circle)=\pi r^2 = \frac{\pi}{4} \\ A(Square)=d^2=1 \\ p=\frac{A(Circle)}{A(Square)}=\frac{\pi}{4} \\ \pi=4p $$
In [20]:
# Solution
from random import random
from math import sqrt
inCircle = 0
sampleCount = 1000
for i in range(sampleCount):
    x = random()
    y = random()
    distance = sqrt((x-0.5)**2+(y-0.5)**2)
    if distance<0.5:
        inCircle +=1
p = inCircle/sampleCount
pi = 4*p
print(pi)
3.24

Your Module¶

Practice¶

  1. 建立一個 lib.py 檔案
  2. 定義 drawSquare() 函式,畫出給定邊長的正方形。
  3. 定義 drawTriangle() 函式,畫出給定邊長的三角形(加分)。

Instructor's Solution¶

In [21]:
from lib import drawSquare
drawSquare(10)
==========
=        =
=        =
=        =
=        =
=        =
=        =
=        =
=        =
==========
project
├── Controller
|   └── controller.py
├── Model
|   ├── items.py
|   └── player.py
└── main.py

在main.py:

from .Controller import controller
from .Model.items import item_names

在controller.py

from ..Model.items import item_names

.<-從檔案的同一層資料夾開始

..<-從檔案的下一層開始

Built-in Modules¶

Resource¶

https://docs.python.org/3/library/

In [22]:
import math
print(math.gcd(91 , 39))
print(math.sin(math.radians(30)))
print(math.e)
print(math.log10(3))
print(math.sqrt(16))
print(math.factorial(5))
print(math.pow(5,4))
print(math.floor(3.7))
13
0.49999999999999994
2.718281828459045
0.47712125471966244
4.0
120
625.0
3
In [23]:
import random
print(random.random()) #[0,1)
print(random.randint(1,100)) #[a,b]

array = list(range(10))
print(random.choice(array))
print(array)
random.shuffle(array)
print(array)
0.006843019492424385
15
0
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 1, 9, 7, 8, 5, 3, 0, 6]
In [24]:
import re
result = re.finditer(".ATC.", "AATCGATACGTCGATCGATTGCA")
print(list(result))
[<re.Match object; span=(0, 5), match='AATCG'>, <re.Match object; span=(12, 17), match='GATCG'>]

In [25]:
import sys
print(sys.platform) 
print(sys.version)
print(sys.executable)
print(sys.copyright)
linux
3.10.10 | packaged by conda-forge | (main, Mar 24 2023, 20:08:06) [GCC 11.3.0]
/home/andreliang/mambaforge/bin/python
Copyright (c) 2001-2023 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
In [26]:
import time
print(time.asctime())
print(time.time())
time.sleep(5)
print(time.time()) 
# extended reading: https://www.youtube.com/watch?v=QJQ691PTKsA
Mon Apr 10 11:22:16 2023
1681096936.6948524
1681096941.6985853
In [27]:
import datetime
print(datetime.datetime.now()) 
print(datetime.date.today())
delta = datetime.timedelta(weeks = 2)
print(datetime.date.today()+delta)
print(datetime.datetime.now().strftime("Year: %Y, seconds: %S"))
2023-04-10 11:22:21.806368
2023-04-10
2023-04-24
Year: 2023, seconds: 21

Practice¶

In [28]:
# Solution
import math
num = math.pow(math.pow(49,1/3), 100)
n = math.floor(math.log10(num))
a = math.pow(10, math.log10(num)-n)
print(n , a)
56 2.1871034934604183

¶

External Modules¶

Resource¶

  1. https://pypi.org/
  2. https://docs.conda.io/en/latest/

pip install <package-name>

Example¶

url: https://pypi.org/project/emoji/

In [29]:
import emoji
print(emoji.emojize('Python is :COOL_button:'))
# list: https://carpedm20.github.io/emoji/all.html?enableList=enable_list_zh
Python is 🆒

Practice¶

安裝維基百科套件 wikipeida 網址:https://pypi.org/project/wikipedia/ ,之後利用這個套件印出你的學校的簡介(如果你的學校沒有維基百科頁面,則印出國立臺灣大學的簡介)

請自行閱讀官網的介紹 網址:https://wikipedia.readthedocs.io/en/latest/code.html#api ,學會如何操作這個套件。

In [30]:
# Solution
import wikipedia
print(wikipedia.summary("National Taiwan University"))
National Taiwan University (NTU; Chinese: 國立臺灣大學; Pe̍h-ōe-jī: Kok-li̍p Tâi-oân Tāi-ha̍k) is a public research university in Taipei, Taiwan.The university was founded in 1928 during Japanese rule as the seventh of the Imperial Universities. It was named Taihoku Imperial University and served during the period of Japanese colonization. After World War II, the Nationalist Kuomintang (KMT) government assumed the administration of the university. The Ministry of Education reorganized and renamed the university to its current name on November 15, 1945, with its roots of liberal tradition from Peking University in Beijing by former NTU President Fu Ssu-nien. The university consists of 11 colleges, 56 departments, 133 graduate institutes, about 60 research centers, and a school of professional education and continuing studies.Notable alumni include Tsai Ing-Wen, current President of the Republic of China, former presidents Lee Teng-hui, Chen Shui-bian and Ma Ying-jeou, Turing Award laureate Andrew Yao, and Nobel Prize in Chemistry laureate Yuan T. Lee. NTU is affiliated with National Taiwan Normal University and National Taiwan University of Science and Technology as part of the NTU System.

Additional Information¶

Reference¶

  1. 2022年北區py班簡報
  2. 好玩的模組們