賴昱錡
討厭程式的小廢物
2025.7.30 Python 語法課程
Richard Lai
一些複習與新東西
基本上就是一般的陣列,但每一個元素都是一個一維陣列
a = [[1, 2, 3], [4, 5, 6]]
print(a[0])
print(a[1])
b = a[0]
print(b)
print(a[0][2])
a[0][1] = 7
print(a)
print(b)
b[2] = 9
print(a[0])
print(b)n = 3
m = 4
a = [[0] * m for i in range(n)]# the first line of input is the number of rows of the array
n = int(input())
a = []
for i in range(n):
row = input().split()
for i in range(len(row)):
row[i] = int(row[i])
a.append(row)建立
輸入二維陣列
def power(a, n):
if n == 0:
return 1
return power(a, n-1) * a
a = float(input())
n = int(input())
print(power(a, n))題目:給定一個正實數 \(a\) 和一個非負整數 \(n\),計算 \(a^n\),但不能使用 ** 運算子或任何內建的函式 (像是 math.pow())
follow up: 有沒有辦法更有效率?
能用現成的就用
Python 的一大特色
有了模組,我們就能使用一些有的沒的功能,包含數據分析、機器學習、撰寫遊戲
可以使用現存的或自己撰寫ㄉ
pip install [module]幾點提醒:
# 最基本的 import
import random
# 簡化名稱
import numpy as np
random_number = random.randint(1, 10)
option = random.choice(["Adam", "Emma"])
a = np.array([(1, 2, 3), (4, 5, 6)])as 可以為引入的套件取別名使用套建中的函式之前需要依照 module.[function] 的格式from random import randint, choice
random_number = randint(1, 10)
option = choice(["Adam", "Emma"])這種寫法可以省略作為前綴的套件名稱
mymodule.py)import qrcode
text = input("請輸入網址: ")
path = input("請輸入檔名 ")
img = qrcode.make(text)
img.save(path)
img.show()pip install pillow, qrcodefrom pytubefix import YouTube
from pytubefix.cli import on_progress
url = input()
yt = YouTube(url, on_progress_callback = on_progress)
print(yt.title)
ys = yt.streams.get_highest_resolution()
ys.download()pip install pytube, pytubefixpytube 原專案在這,但我自己運行時會有網路上的問題,因此改成使用較新的 pytubefix
pygame: 遊戲設計
pandas: 數據分析
matplotlib: 繪製圖表
.....
Everything is an object.
Class (類別)
可以比喻為一張藍圖,根據不同的屬性,可以建構出不同的物體。
物件 (Object)
class Human():
def __init__(self, life, age, hair, money):
self.life = life
self.age = age
self.hair = hair
self.money = money__init__(): 初始化一個物件,self 是必要的參數,代表物件本體
self.life: 代表物件的一個屬性 (instance attributes)life: init 函式中所傳入的參數
a = Human(True, 25, "Blonde", 12345678)
print(a.life, a.age, a.hair, a.money)取用一個物件的屬性 (attributes) 的方法是在 instance 名稱的後面加一點。修改或刪除也是
像是: instance.attr 這樣的格式
a.age = 50
del a.moneyclass Human():
def __init__(self, life, age, hair, money):
self.life = life
self.age = age
self.hair = hair
self.money = money
def howOld(self):
print(f"is {self.age} years old")
a = Human(True, 25, "Blonde", 12345678)
a.howOld()def greeting(name, country="German", words="Good morning"):
print(f"Hello {name} from {country}, {words}")
greeting("Mike", "Canada", "What\'s up")
greeting("May", "Taiwan")
greeting("Maxwell")class Human():
def __init__(self, life, age, hair="Black", money=100):
self.life = life
self.age = age
self.hair = hair
self.money = money
def howOld(self):
print(f"is {self.age} years old")
mary = Human(False, 25)
mary.howOld()class Human():
def __init__(self):
passBy 賴昱錡
2025.7.30 Python 語法課程