Python 直譯器使用方式
開啟終端機輸入如下
先在Visual Stidio 創建hello_world.py (python檔案)
內文輸入 print('Hello world')
開啟python檔案則在終端機輸入
$python hello_world.py
即可開啟
往後訓練皆會使用Jupyter notebook
繪圖練習
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.random.randn(50).cumsum())
按下Run
接下來要介紹Python語言寫法
以for迴圈來舉例:
for x in array:
if x < pivot:
less.append(x)
else:
greater.append(x)
註解
任何文字、字串、字符前加入 # 即可
# 我是註解
變數和參數傳遞
皆為右邊的值賦予左邊的變數
x = [1, 2, 3, 4, 5]
Python為強型態
a = '123'
print(a + 123) 此行會報錯誤
因為 a 為字串, 123為數值故不能直接做運算
引用外部函式
假設有一檔案為 test.py
內部程式為:
def testFun(x):
return x + 5
另一檔案要使用外部檔案函式 test2.py
內部程式為:
import test
result = test.testFun(22)
或者
from test import testFun
或者
import test as t
from test import testFun as tFun
t1 = t.fFun(22)
以上三種寫法皆可
運算子與比較
a + b a 加 b
a - b a 減 b
a * b a 乘 b
a / b a 除 b
a // b a 除 b 取整數
a ** b a 的 b 次方
a & b a 且 b 皆為 True,結果為True
a | b a 或 b 為 True,結果為True
a ^ b a 或 b 其中一者為True,但不能同為True,結果為True
a == b a 和 b 相等,結果為True
a != b a 和 b 不相等,結果為True
a < b, a <= b a 小於 b 或 a 小於等於 b,結果為True
a > b, a >= b a 大於 b 或 a 大於等於 b,結果為True
範例
In [33]: 5 - 22
In [34]: -17
In [35]: 5 <= 22
In [36]: False
未完待更新....