# 變數 a = 3 # 型態:str, int, bool, float, list, dict, NoneType, type # 檢查型態:type() print(type(a), type("a"), type(1.2), type([]), type(None)) # 轉型 b = str(a) print(b, type(b))
# 輸入 s = input() print(type(s)) # str type # 輸出:間隔、結尾 print("a", "b", sep=' ya ', end=' yaya ') # 跳脫字元 s = "a\nb" print(s) p = "a\\nb" print(p)
# int, float: +, -, *, /, //, **, % print(3+2, 3-2, 3*2, 3/2, 3//2, 3**2, 3%2) # str: +, * print('a'+'b', 'a'*10) # assign: +=, -=, ... a = 1 a += 2 print(a)
# 關係運算:>, <, ==, !=, >=, <= print(3>2, 3<2, 3==2, 3!=2, 3>=2, 3<=2) # 邏輯運算 -> 產生 bool expression: c1 = (3 > 2) c2 = (3 < 2) print(c1 and c2, c1 or c2, not c1)
if expression: statement(s) elif expression2: statement(s) else: statement(s)
score = int(input()) if score < 60: print('F') elif score < 80: print('C') elif score < 90: print('B'): else: print('A')
while expression: statement(s) if expression: continue # 跳過這次回圈(剩下的 code) if expression: break # 跳出 while
n = int(input()) i = 2 prime = True while i < n: if n % i == 0: prime = False break i += 1 print(prime)
i = 0 while i < 10: if i == 5: continue print(i)
# iterable: list, dict, range, string... # range(start, stop, step), 左閉右開 for [variable] in [iterable]: statement(s)
for i in range(1, 10): for j in range(1, 10): print(i, 'x', j, '=', i*j, sep='', end=' ') print()
for prime in [2, 3, 5, 7, 11]: print(prime)
# list 可以放任何 type 的東西,包括 list a = [1, 2, '3', 4.5, [6, 7, 8]] # 長度? print(len(a)) # 取值,改值: 0 <= idx < len(a), -len(a) <= idx <= -1 print(a[0], a[-1]) a[0], a[-1] = 1, 2 print(a[0], a[-1])
# 遍歷: i=index, v=value for i, v in enumerate(a): print(i, v) # function: min, max, sum a = [1, 2, 3] print(min(a), max(a), sum(a)) # Method a.append(4) a.pop() a.index(3) a.clear()
# slicing b = a[start : stop : step] # copy b = a[:] # map a = list(map(int, input().split())) print(a)
# 建立 dictionary d = {1:2, 2:3, '3':4} # {key: value...} # 長度(個數) print(len(d)) # 取值 print(d[1], d['3']) print(d[3]) # key 不在裡面會爛掉 # 檢查 key print(3 in d, '3' in d) # 新增&修改 d[3] = 4 d['3'] = 123 print(d[3], d['3'])
# 遍歷 for k, v in d.items(): print(k, v) # 刪除某個 (key, value) d.pop(3) # 清空 d.clear()
# 建立: 雙引單引都可以 print('123', "123") # 比大小:字典序 s, p = 'abcb', 'abdb' print(s > p) # 函數 # 取代 print(s.replace('b', 'd')) # s.replace(字串串, 新字串) # 去頭尾 print(' 123 '.strip()) # s.strip(要去除的字元們) 預設空白 # 分割 print(s.split('bc')) # s.split(sep字串串) # 搜尋 print(s.find('bc')) # s.find(要找的字串串, 開始=0, end=無限大), 找不到回傳 -1 # 結合 print(','.join(['a', 'b', 'c'])) # 結合字元.join(list of str)
for i in range(1, 10): for j in range(1, 10): print('{:1}x{:1}={:2}'.format(i, j, i*j), end=' ') print()
def 函數名稱(變數1, 變數2, 變數3=預設值): statement(s) return 結果
def f(a, b, c=1, d=2): s = a + b + c p = a + b + c + d return s, p r1, r2 = f(1, 2, 3, 4) print(r1, r2) print(f(1, 2, d=3))
# 好多種 import 的方式 import math import math as m from math import gcd from math import gcd as ggggggcd print(math.gcd(4, 6)) print(m.gcd(4, 6)) print(gcd(4, 6)) print(ggggggcd(4, 6))