# Python 第四堂 四則運算、for迴圈 ## 加減乘除 ```python= a = 10 b = 5 print(a + b) # 加法 print(a - b) # 減法 print(a * b) # 乘法 print(a / b) # 除法 print(a // b)# 除法,但捨去小數 print(a % b) # 取餘數 print(a ** b)# 次方 ``` ## 除法及餘數 ```python= a = 13 b = 5 print(a / b) # 除法,會取小數點 print(a // b)# 除法,但捨去小數 print(a % b) # 取餘數 被b除餘... ``` ```python= for i in range(100): if i % 5 == 2: print(i) ``` ## sum 累加 ```python= # sum用法 array = [5, 6, 7] print(sum(array)) # sum()是python內建的函式,這邊用s命名避免衝突 s = 0 for i in range(101): s += i # s = s + i print(s) ``` ## 用list來儲存 1加到100的結果 ```python= l = list() s = 0 for i in range(101): s += i # s = s + i l.append(s) # print(l) for i in l: print(i) ``` ## input 使用者輸入 ```python= a = 5 print(a) a = input("請輸入數字: ") print(a) ``` ### input 接收到的為字串格式 ```python= a = int(input("請輸入數字: ")) print("您輸入的數字:", a) for i in range(1, a+1): print(i) ``` ### type 格式 ```python= a = input("請輸入數字: ") print(type(a)) b = 6 print(type(b)) ``` ## 判斷是否為數字 isdigit ```python= a = "123" print(a.isdigit()) a = "12AB3" print(a.isdigit()) ``` ## 判斷是否為英文字母 isalpha ```python= a = "ABC" print(a.isalpha()) a = "12AB3" print(a.isalpha()) ``` ## 中華民國身分證字號 ```python= ID = "A123456789" print(ID[0].isalpha()) print(ID[1:10].isdigit()) #for c in ID: # char # print(c.isdigit()) ``` ```python= ID = input("請輸入身份證字號:") if len(ID) == 10: # 判斷長度 if ID[0].isalpha() and ID[1:10].isdigit(): # 再判斷字母及數字 print("您輸入的格式正確", ID) else: print("格式錯誤", ID) else: print("身分證字號長度不符") ```