---
title: python讀書會(三)
tags: python讀書會
---
{%hackmd @themes/orangeheart %}
## 3.0 回顧...
1. 引入套件並且將外掛重新命名(```from```、```import```、```as```)
2. ```if```指令(```else```)
3. 普通函式及回傳)(```def```、```return```、```class```)
4. 迴圈(```for```、```while```)
:::success
:question: 請寫出一段用來判斷此數字是否為完全平方數的程式。
:question: 微積分好困難,利用電腦寫出可以解決不定積分的函式,你要使用套件我也不反對。(先從自然數次方的多項式函數下手,再去考慮其他種類的函數)
:question: 利用程式找出所有的**水仙花數**~~
:::
:notes:還有其他有趣性質的數字:四葉玫瑰數、孿生數、普洛尼克數、虧數、奢侈數...
## 3.1 keywords

#### 3.1.1 break, continue
```break```、```continue```通常用在迴圈內部來實現操縱迴圈停止或是繼續的自由!!
- [x] 程式碼 3.1.1a
```=python
for m in "string":
if m == "i":
break ##只有輸出到i而已
print(m)
print("The end")
```
- [x] 程式碼 3.1.1b
```=python
for m in "string":
if m == "i":
continue ##只有i不輸出
print(m)
print("The end")
```
#### 3.1.2 async, await
又是一個幾乎不會使用到的keyword...
但```async```**異步**功能很強大,但今天不會細說~
首先,用到```async```就要先```import asyncio```,這個keyword基本上在任何語言都可以使用!!
**Concurrency 並發性 :** 同時管理多個指令序列。只需一個core
**parallelism 並行性 :** 同時運行多個指令序列。需要不只一個core
**Threading 線程 :** 一種並發執行模型。

- [x] 程式碼 3.1.2a
```=python
import time
def dosomething(i):##當我使用普通函數
print(f"第 {i} 次開始")
time.sleep(2)
print(f"第 {i} 次結束")
if __name__ == "__main__":
start = time.time()
for i in range(5):
dosomething(i+1)
print(f"time: {time.time() - start} (s)")
```
- [x] 程式碼 3.1.2b
```=python
import time
import asyncio
import nest_asyncio
nest_asyncio.apply()
async def dosomething(i):##當我使用async函數
print(f"第 {i} 次開始")
await asyncio.sleep(2)
print(f"第 {i} 次結束")
if __name__ == "__main__":
start = time.time()
tasks = [dosomething(i+1) for i in range(5)]
try:
asyncio.run(asyncio.wait(tasks))
except:
pass
finally:
print(f"time: {time.time() - start} (s)")
```
**<font color = #6600cc>有任何程式上需要資源或是解決問題,都可以去  或是  以解決你的問題~~</font>**
#### 3.1.3 except, raise, try, finally
這一組的keywords主要用來debugs。
我們程式可能執行的時候會出現錯誤,然後碰到錯誤的這時編譯器會停下...可是我希望它執行完以後再告訴我我的疏漏,甚至是我要更明白告訴使用者它不應該做什麼,於是就要用到這些keywords!
```try```可以用來抓errors,```except```相當於遇到errors要幹嘛。
- [x] 程式碼 3.1.3a
```python=
try:
Try-block
except exception1:
Exception1-block
except exception2:
Exception2-block
else:
Else-block
###如果沒有任何錯誤,就會來到這一步~
###但如果錯了,那就不會到這一步
finally:
Finally-block
###即便你錯得再離譜,它終究會執行!通常是在執行文件內容要記得關閉時用到
```
- [x] 程式碼 3.1.3b
```python=
import sys #引入sys可以知道bug的類型
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("在執行", entry)
r = 1/int(entry)
break
except:
print(sys.exc_info()[0], "此型態錯誤發生!!")
print("換下一個")
print()
print(entry, "的倒數是", r)
#################分隔線###############################
##(import sys #引入sys可以知道bug的類型)這句已經不存在了
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("在執行", entry)
r = 1/int(entry)
break
except Exception as e:
print(e.__class__, "此型態錯誤發生!!")
print("換下一個")
print()
print(entry, "的倒數是", r)
```
```except```則是可以抓指定類型的error:
- [x] 程式碼 3.1.3c
```python=
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass
```
- [x] 程式碼 3.1.3d
```python=
try:
f = open("demofile.txt") ##這是一個不可寫的文件
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
```
```raise```是故意引發異常,好讓我們知道程式沒有輸出任何結果原因為何。
- [x] 程式碼 3.1.3e
```python=
x = -1
##原本這段程式碼是不會出現問題的
if x < 0:
raise Exception("Sorry, no numbers below zero")
```
#### 3.1.4 assert, with, yield
```assert```也是一個跟程式錯誤有關的keyword;```with```則是可以簡化程式碼的手段;```yield```類似於```return```,只是```return```返回的是函數,```yield```返回的是生成器!
- [x] 程式碼 3.1.4a
```python
##這段程式
assert condition, message
##等效於:
if not condition:
raise AssertionError(message)
```
- [x] 程式碼 3.1.4b
```python=
a = 4
assert a > 5, "The value of a is too small"
```
- [x] 程式碼 3.1.4c
```python=
# 1)
file = open('file_path', 'w')
file.write('hello world !')
file.close()
# 2)
file = open('file_path', 'w')
try:
file.write('hello world')
finally:
file.close()
##這兩段作用相同,但我們可以用with簡化它
```
- [x] 程式碼 3.1.4d
```python=
with open('example.txt', 'w') as my_file:
my_file.write('Hello world!')
```
- [x] 程式碼 3.1.4e
```python=
def generator():
for i in range(6):
yield i*i
g = generator()
for i in g:
print(i)
```
**當你成功安裝了python!**

## Exercise成果
找出1~1000000之間所有水仙花數。
- [x] 程式碼 陳漢凭
```python=
for n in range(1000000):
m=0
d=0
long = len(str(n))
for i in range(long):
d=(n//(10**(long-i))*(10**(long-i)))
m=m+((n-d)//(10**(long-i-1)))**long
if n == m:
print(n)
```