owned this note
owned this note
Published
Linked with GitHub
# 2024/08/06 自定義模組 input() eval() enumerate() append() 串列新增
> [TOC]
導覽一些重要模組,日後課堂有講解
# 自定義模組
```
def func(參數,...):
函式區塊
return 運算式
```
<!-- 程式範例來源:ooxx
```
def hello(name, age):
msg = f'{name} is {age} years old'
print(msg)
hello('oxxo',18) # oxxo is 18 years old
hello(18,'oxxo') # 18 is oxxo years old ( 因為 18 和 oxxo 對調,所以結果就會對調 )
hello(age=18,name='oxxo') # oxxo is 18 years old ( 使用關鍵字引數,結果就會是正確的 )
``` -->
畫圓形,使用自定義外來模組
```python=
import turtle
import random
import colorlist
print(len(colorlist.color_list))
window_width = 1400
window_height = 700
color_list = colorlist.color_list
def get_random_color():
return random.choice(color_list)
def update_color():
global one_color
one_color = get_random_color()
turtle.ontimer(update_color, 1000) # 每 3 秒更新一次顏色
one_color = get_random_color()
print(one_color)
sc = turtle.Screen()
sc.setup(window_width, window_height)
sc.bgcolor("#FEFAE0")
sc.tracer(0)
# 建立海龜對象
tu = turtle.Turtle()
tu.pensize(0) # 設置筆畫粗度
# 初始化定時器來更新顏色
update_color()
print("turtle moving")
radius = 30
dx = 5
dy = 5
x = (-window_width / 2) + radius
y = (-window_height / 2) + radius
while True:
tu.clear()
colorlist.gen_circle(tu, x, y, radius, one_color)
x += dx
y += dy
# print(f"x: {x}, y: {y}, dx: {dx}, dy: {dy}")
# 如果到達邊界則改變方向
if x >= (window_width // 2 - radius) or x <= (-window_width // 2 + radius):
dx = -dx
if y >= (window_height // 2 - radius) or y <= (-window_height // 2 + radius):
dy = -dy
sc.update()
# 保持窗口打開
sc.mainloop()
```
```python=
color_list = ['white','red']
def gen_square(tu, x, y, w, h, colorname='black', r=0, g=0, b=0):
"""
有內定值要寫在後面
x:
y:
:return:
"""
tu.penup()
tu.goto(x,y)
tu.pendown()
if colorname is None:
tu.pencolor((r, g, b)) # 設置筆畫顏色
tu.fillcolor(r, g, b)
else:
tu.pencolor(colorname) # 設置筆畫顏色
tu.fillcolor(colorname)
tu.hideturtle()
tu.begin_fill()
for _ in range(2):
tu.forward(h)
tu.left(90)
tu.forward(w)
tu.left(90)
tu.end_fill()
tu.penup()
return None
def gen_circle(tu, x, y, radius, colorname='black', r=0, g=0, b=0):
"""
生成一個圓形,並以圓心為基準點
x: 圓心的 x 坐標
y: 圓心的 y 坐標
radius: 圓的半徑
colorname: 顏色名稱(默認為黑色)
r, g, b: 顏色的 RGB 值(如果未指定顏色名稱)
"""
tu.penup()
tu.goto(x, y - radius) # 移動到圓的底部中點
tu.pendown()
if colorname is None:
tu.pencolor((r, g, b)) # 設置筆畫顏色
tu.fillcolor(r, g, b)
else:
tu.pencolor(colorname) # 設置筆畫顏色
tu.fillcolor(colorname)
tu.hideturtle()
tu.begin_fill()
tu.circle(radius) # 繪製圓形
tu.end_fill()
tu.penup()
return None
```
# input 輸入
`a = input("字串")`
# if elif
# for 裡面有 else
```python=
for n in range(2, 10): # 外層迴圈,n 從 2 到 9
for x in range(2, n): # 內層迴圈,x 從 2 到 n-1
if n % x == 0: # 如果 n 能被 x 整除,表示 n 不是質數
print(n, 'equals', x, '*', n // x) # 打印 n = x * (n // x)
break # 跳出內層迴圈
else:
# 內層迴圈正常結束(沒有找到任何能整除 n 的數)
print(n, 'is a prime number') # 打印 n 是質數
n = 2 不會做
```
# enumerate(iterable, start=0)
iterable 可迭代物件
列舉函式
串列裡面可以有很多元素
```python=
for i, v in enumerate(['a','b','c'])
print(i, v)
```
```
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))
print(list(enumerate(seasons, start=1)))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
```
```python=
[0,1,2]
[(0,'Z'),(1,'A')]
元素 item 可以是 tuple 元祖
```
# eval()
將 運算式字串 數值化
```
x = 1
eval('x+1')
```
# range()
產生 數字索引物件
# zip()
垂直打包
# sum()
加總 / len(list) = 平均
# 串列生成式
python 語法糖
```
list1 = []
for n in range(1,11)
if n%2 == 0:
list1.append(n*n)
等同於
list2 = [ n*n for n in range(1,11) if n%2 == 0]
```
```
def is_prime(num):
if num < 2:
return False
for x in range(2, int(num**0.5) + 1):
if num % x == 0:
return False
return True
# 使用串列生成式列出 1 到 100 的質數
prime_numbers = [num for num in range(1, 101) if is_prime(num)]
print(prime_numbers)
```
# 串列 list.append
串列教學範例:
https://hackmd.io/@ShahonG/Hy6OV_jSL
串列增加範例:
```python=
numbers = []
for x in range(10):
numbers.append(x * 3)
print(numbers)
numbers = [x * 3 for x in range(10) if x > 4]
print(numbers)
```