Try   HackMD

Python基本語法

作者:王一哲
第1版:2018年3月6日
第2版:2022年7月4日
第3版:2024年9月19日,加上附錄


資料型態

在C或C++中常見的資料型態有以下幾種

  • char 字元
  • short 短整數
  • unsigned short 沒有正負號的短整數
  • int 整數
  • unsigned int 沒有正負號的整數
  • long 長整數
  • unsigned long 沒有正負號的長整數
  • float 浮點數
  • double 倍精數
  • bool 布林值,只有0或1

而在 Python 當中,基本上只有分為

  • str 字串
  • int 整數
  • float 浮點數
  • bool 布林值

直譯器會自動依照資料判斷型態,例如

  • A 會被判斷為 str
  • 1 會被判斷為 int
  • 1.1 會被判斷為 float
  • True 或 False 會被判斷為 bool

變數

我們可以將變數當作儲存資料的容器,為變數命名時有以下幾點注意事項:

  1. 可以使用英文字母、數字及符號,字母有區分大、小寫,例如 a、A、b1、B2、c_3 都是符合規則的變數名稱。
  2. 不能以數字開頭,例如 0d 就不符合規則。
  3. 不能使用系統保留字,這些字有特殊的用途,不需要全部背下來,在程式碼編輯器中會自動將這些字上色。保留字有以下這些:and、as、assert、async、await、break、class、continue、def、del、elif、else、eval、except、finally、for、format、from、global、if、import、in、input、int、is、lambda、len、max、nonlocal、not、or、pass、print、raise、range、return、str、try、while、with、yield、False、None、True
  4. 使用有意義的變數名稱,最好能讓人一眼看出這個變數的用途,例如將儲存物體長度的變數命名為 length。
  5. 理論上在 Python 當中可以使用統一碼 Unicode 的字元作為變數名稱,但為了避免程式碼在其它的作業系統開啟時變成亂碼,建議還是使用英文字母、數字、符號就好。

在C、C++中建立變數時,我們需要同時指定變數對應的資料型態,例如

int a;
float b;
char c;

在Python中則不需要指定變數對應的資料型態,直譯器會自動根據儲存到變數中的資料自動判斷型態,最好養成在建立變數時同時指定初始值的習慣,例如

a = 0
b = 1.1
c = 'c'
d = 'AaBbCc'
e = True
f = False

在 Python、C、C++ 及大部分的程式語言當中,等號 = 用來指定數值給變數,例如 a = 2 是將 2 這個數值指定給變數 a;若要比較兩個變數是否相等,要使用 ==,這與數學式子的寫法不相同,需要適應一下。


如果在 Python Shell 當中想要知道某個變數對應的資料型態,可以使用

type(變數名稱)

以剛才建立的變數為例,a、b、c、d、e、f的回傳值分別為

<class 'int'>
<class 'float'>
<class 'str'>
<class 'str'>
<class 'bool'>
<class 'bool'>

判斷條件:if

最簡單的語法為

if 條件:
    條件成立時執行的程式碼

當條件成立時執行冒號下的程式碼,程式碼必須從 if 的位置開始縮排,假設使用的縮排為 4 個空格,則在條件成立時要執行的程式碼每行都要縮排 4 個空格,若某一行沒有縮排,從此行開始會被視為 if 的部分已經結束。如果條件成立時執行的程式碼只有一行,可以直接放在冒號之後不需換行。

如果要加上條件不成立時執行的程式碼,語法為

if 條件:
    條件成立時執行的程式碼
else:
    條件不成立時執行的程式碼
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
if … else … 流程圖

如果條件不只有一個,可以使用多層的 if,語法為

if 條件1:
    條件1成立時執行的程式碼
elif 條件2:
    條件1不成立、條件2成立時執行的程式碼
else:
    條件12皆不成立時執行的程式碼
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
if … elif … else … 流程圖

程式 2-1:if 的使用方法

a = eval(input("a = ")) b = eval(input("b = ")) if a > b: print("a > b") else: print("a <= b") if a > b: print("a > b") elif a == b: print("a = b") else: print("a < b")

執行時先由使用者用鍵盤輸入 a、b 的值,由於輸入的資料會被視為字串,加上 eval 將字串轉換為整數或浮點數。第一個 if 是:當 a > b 時印出文字 a > b,若條件不成立則印出文字 a <= b。第二個 if 是:當 a > b 時印出文字 a > b,當 a == b 時印出文字 a = b,若條件不成立則印出文字 a < b。

重複執行:while 迴圈

在程式語言當中經常會重複執行某一段程式碼,這樣的語法稱為迴圈 (loop),其中一種迴圈稱為 while,語法為

while 條件:
    條件成立時執行的程式碼

當條件成立時執行冒號下的程式碼,一直重複執行到條件不成立時為止。條件成立時執行的程式碼一樣要注意程式碼縮排的空格數。while 迴圈的流程圖如下

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
while 迴圈流程圖

程式 2-2:使用 while 迴圈計算 1 + 2 + 3 + … + 10

result = 0 i = 1 n = 10 while i <= n: print("i =", i) result += i i += 1 print("result =", result)

先定義變數 i、n、result 指定數值。當 i <= n 時執行 while 迴圈中的程式碼,印出 i 的數值、將 result 的數值 +i 並重新指定給 result,將 i 數值 +1 並重新指定給 i。當 while 迴圈執行完之後印出文字 result = 以及 result 的數值。這個程式是用來計算 1 + 2 + 3 + … + 10 = ?

問題:如果想計算的是 1 + 3 + 5 + 7 + 9 = ? 要怎麼寫呢?(提示:只要改一個地方即可。)


程式 2-3:使用 while 迴圈及輾轉相除法計算最大公因數

a = 276 b = 437 i = 0 print("i\ta\tb") while b: r = a%b a = b b = r i += 1 print("{:d}\t{:d}\t{:d}".format(i, a, b)) gcd = a print("gcd =", gcd)

加上第3、5、11行程式碼,可以看到 while 迴圈每次運作時變數 a、b 的數值,執行程式時輸出為

i	a	b
1	437	276
2	276	161
3	161	115
4	115	46
5	46	23
6	23	0
gcd = 23

2025年2月27日更新,行數比較少的寫法

a, b, i = 276, 437, 0 print("i\ta\tb") while b: a, b = b, a%b i += 1 print(f"{i:d}\t{a:d}\t{b:d}") print(f"gcd = {a:d}")

重複執行:for 迴圈

Python 的 for 迴圈和其它的程式語言很不一樣,比較像是用來從一串資料中依序讀取當中的元素來運算,經常搭配 range 或串列(list)資料一起使用。以搭配 range 為例

for i in range(5):
    print(i)

range是用來產生數列的函式,格式為

range(起始值, 結束值, 增量)

起始值預設為0,增量預設為1,但產生的數列不包含結束值。因此上面的程式碼執行時,會將 ragne(5) 產生的數列 (0, 1, 2, 3, 4) 依序讀取出來並指定給變數 i,最後將印出 i 的數值,因此執行結果為

0
1
2
3
4
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
for 迴圈流程圖

程式 2-4:使用 for 迴圈計算 1 + 2 + 3 + … + 10

result = 0 for i in range(1, 11): print("i =", i) result += i print("result =", result)

這個程式和程式 2-2 一樣是用來計算 1 + 2 + 3 + … + 10 = ?

問題:如果想計算的是 1 + 3 + 5 + 7 + 9 = ? 要怎麼寫呢?(提示:只要改一個地方即可。)


雙層迴圈

我們可以在迴圈之中再加上另一個迴圈,變成雙層迴圈的結構,這通常會用在有兩個變數需要重複執行的狀況。例如以下的程式碼

for i in range(3): for j in range(3): print(f"i = {i:d}\tj = {j:d}")

執行的結果為

i = 0	j = 0
i = 0	j = 1
i = 0	j = 2
i = 1	j = 0
i = 1	j = 1
i = 1	j = 2
i = 2	j = 0
i = 2	j = 1
i = 2	j = 2

由結果可以看出,外層的迴圈第一次運作時 i = 0,接下來進到內層的迴圈,內層迴圈運作時 j 的值依序為 0、1、2;再回到外層的迴圈,此時 i = 1,再執行內層的迴圈3次;再回到外層的迴圈,此時 i = 2,再執行內層的迴圈3次.如果想要用 while 迴圈印出同樣的值,可以採用以下的寫法

i = 0 while i < 3: j = 0 while j < 3: print(f"i = {i:d}\tj = {j:d}") j += 1 i += 1

我們可以使用雙層迴圈印出九九乘法表,由於我們可以事先確定迴圈運作的次數,使用 for 迴圈的寫法看起來會比較簡潔。

for i in range(2, 10): for j in range(2, 10): if j < 9: print(f"{i:d} * {j:d} = {i*j:d}", end="\t") else: print(f"{i:d} * {j:d} = {i*j:d}")

其中第3 ~ 6行可以改寫成這樣

print(f"{i:d} * {j:d} = {i*j:d}", end="\t" if j < 9 else "\n")

當然也可以用 while 迴圈做到一樣的效果。

i = 2 while i <= 9: j = 2 while j <= 9: if j < 9: print(f"{i:d} * {j:d} = {i*j:d}", end="\t") else: print(f"{i:d} * {j:d} = {i*j:d}") j += 1 i += 1

其中第5 ~ 8行可以改寫成這樣

print(f"{i:d} * {j:d} = {i*j:d}", end="\t" if j < 9 else "\n")

以下是輸出的結果。

2 * 2 = 4	2 * 3 = 6	2 * 4 = 8	2 * 5 = 10	2 * 6 = 12	2 * 7 = 14	2 * 8 = 16	2 * 9 = 18
3 * 2 = 6	3 * 3 = 9	3 * 4 = 12	3 * 5 = 15	3 * 6 = 18	3 * 7 = 21	3 * 8 = 24	3 * 9 = 27
4 * 2 = 8	4 * 3 = 12	4 * 4 = 16	4 * 5 = 20	4 * 6 = 24	4 * 7 = 28	4 * 8 = 32	4 * 9 = 36
5 * 2 = 10	5 * 3 = 15	5 * 4 = 20	5 * 5 = 25	5 * 6 = 30	5 * 7 = 35	5 * 8 = 40	5 * 9 = 45
6 * 2 = 12	6 * 3 = 18	6 * 4 = 24	6 * 5 = 30	6 * 6 = 36	6 * 7 = 42	6 * 8 = 48	6 * 9 = 54
7 * 2 = 14	7 * 3 = 21	7 * 4 = 28	7 * 5 = 35	7 * 6 = 42	7 * 7 = 49	7 * 8 = 56	7 * 9 = 63
8 * 2 = 16	8 * 3 = 24	8 * 4 = 32	8 * 5 = 40	8 * 6 = 48	8 * 7 = 56	8 * 8 = 64	8 * 9 = 72
9 * 2 = 18	9 * 3 = 27	9 * 4 = 36	9 * 5 = 45	9 * 6 = 54	9 * 7 = 63	9 * 8 = 72	9 * 9 = 81

結語

Python 的功能非常多,但是我們的目標是利用 VPython 做物理模擬動畫,我們只需要 if、while、for 再加上一些儲存資料的容器就夠用了,在之後的動畫教學中會慢慢介紹更多不同的格式。


附錄,以上這些程式改用 C++ 的寫法

程式 2-1:if 的使用方法

#include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; if (a > b) cout << "a > b\n"; else cout << "a <= b\n"; if (a > b) cout << "a > b\n"; else if (a == b) cout << "a = b\n"; else cout << "a < b\n"; return 0; }

程式 2-2:使用 while 迴圈計算 1 + 2 + 3 + … + 10

#include <iostream> using namespace std; int main() { int result = 0, i = 1, n = 10; while(i <= n) { cout << "i = " << i << "\n"; result += i; i++; } cout << "result = " << result << "\n"; return 0; }

程式 2-3:使用 while 迴圈及輾轉相除法計算最大公因數

#include <iostream> using namespace std; int main() { int a = 276, b = 437, i = 0; cout << "i\ta\tb\n"; while (b) { int r = a%b; a = b; b = r; i++; cout << i << "\t" << a << "\t" << b << "\n"; } cout << "gcd = " << a << "\n"; return 0; }

程式 2-4:使用 for 迴圈計算 1 + 2 + 3 + … + 10

#include <iostream> using namespace std; int main() { int result = 0; for(int i=1; i<=10; i++) { cout << "i = " << i << "\n"; result += i; } cout << "result = " << result << "\n"; return 0; }

九九乘法表,for 迴圈版本

#include <iostream> using namespace std; int main() { for(int i=2; i<=9; i++) for(int j=2; j<=9; j++) cout << i << " * " << j << " = " << i*j << "\t\n"[j == 9]; return 0; }

九九乘法表,while 迴圈版本

#include <iostream> using namespace std; int main() { int i = 2; while(i <= 9) { int j = 2; while(j <= 9) { cout << i << " * " << j << " = " << i*j << "\t\n"[j == 9]; j++; } i++; } return 0; }


tags: VPython