[PYTHON] 基礎語法篇
PYTHON 的應用層面十分廣大,
現在就從基礎開始學習吧~
< Prior Knowledge >
print() 是輸出函數,
'hello, world' 是一字串型態的參數。
100 是一整數型態的參數。
< Type and Variable >
變數型態:
< Prior Knowledge >
- PYTHON 的執行是直譯器(依照程式碼一行一行依序執行)。
- 執行環境:IDLE、Anaconda。
< Beginning >
print('hello, world')
'hello, world' 是一字串型態的參數。
print(100)
< Type and Variable >
print(type('hello, world')) # <class 'str'>
print(type(123)) # <class 'int'>
- int:integer 整數型態。
- str:string 字串型態,以 "" 或是 '' 包圍字串。
- float:小數型態(浮點數型態)。
- bool:boolean 布林值型態,True 代表 1,False 代表 0。
- NoneType:沒有型態。
- complex:複數型態,以 A+Bj 表示。
- + 加法運算子:int, str, float, bool, complex。
- − 減法運算子: int, float bool, complex。
- ∗ 乘法運算子:int, str, float, bool, complex。
- / 除法運算子:int, float, bool, complex。
- // 整數除法運算子:int, float, bool, complex。
- % 餘數運算子:int, float, bool。
- ∗∗ 指數運算子:int, float, bool, complex。
- 字串形態的 + 加法運算僅限於兩字串形態相加,若「字串 + 整數」或「整數 + 字串」(整數可替換為其它形態),會發生執行錯誤。
print('hello, world' + 100)
# TypeError: can only concatenate str (not "int") to str
- 字串形態的 ∗ 乘法運算僅限於「字串 ∗ 整數」或是「整數 ∗ 字串」(只能整數)。
print('hello, world' * 2) # 意同於 print(2 * 'hello, world')
# hello, worldhello, world
print('hello, world' * 2.5)
# TypeError: can't multiply sequence by non-int of type 'float'
print('hello, world' * 'hello, world')
# TypeError: can't multiply sequence by non-int of type 'str'
型態轉換:
指定變數:
< If >
關係運算子:
邏輯運算:int('100')
# 從字串轉為整數型態
str(2.5)
# 從浮點數轉為字串型態
n = 100
# 設定整數變數 n,並賦值為 100
s = 'hello, world'
# 設定字串變數 s,並賦值為 'hello, world'
- 變數名稱不可數字開頭。
- 變數名稱可以用全形中文字命名(PYTHON 可以,其它語言大部分不行)。
s = input()
- 讀入為字串形態。
- 讀入為一整行,不會因讀到空白而停止。
- n = n + 2 ⟶ n += 2
- n = n − 2 ⟶ n −= 2
- n = n ∗ 2 ⟶ n ∗= 2
- n = n / 2 ⟶ n /= 2
- n = n // 2 ⟶ n //= 2
- n = n % 2 ⟶ n %= 2
print(value, ..., sep = ' ', end = '\n')
- 傳入多個參數,以逗號隔開。
- 間隔預設是一個空白鍵,可以透過更改 sep 參數改變。
- 結尾預設是一個換行字元,可以透過更改 end 參數改變。
print(1, 2, 3) # 1 2 3
print(1, 2, 3, sep = '_') # 1_2_3
print(1, 2, 3, end = '...') # 1 2 3...
< If >
關係運算子:
- >:大於。
- >=:大於等於。
- <:小於。
- <=:小於等於。
- ==:等於。
- !=:不等於。
ans = (1 != 2)
print(ans) # True
ans = (1 > 2)
print(ans) # False
- and:
and | True | False |
True | True | False |
False | False | False |
- or:
or | True | False |
True | True | True |
False | True | False |
- not:
True | False | |
not | False | True |
if 用法:
< Loop >
loop 稱為迴圈,
分為兩種:
當 expression 成立時,
就一直重複執行縮排內的 statements,
直到 expression 為 False 時即停止。
用法:
2. for loop
用一個變數 i 迭代一個可迭代的物件。
常見可迭代物件:
< Function >
在了解 function 之前,
其實我們已經先用很多 function 了。
預設參數(Default Arguement):
function 看似多了個步驟,
用起來還要注意細節,
十分麻煩。
但其實 function 對於重複性質高程式碼,
可帶來很大的便利。
還有「匿名函數(lambda function)」可以用。
冒號前面是參數,
冒號後面是回傳值。
對於只需使用一次的函數,
通常會用匿名函數表示。
< Import >
import module,
顧名思義就是導入模組,
由於簡化程式碼長度,
可以導入已經寫好的模組使用。
導入方式(以 math 為例):
事實上,
還有很多模組要透過網路下載,
有些 OJ 並不能使用,
而這些模組就是 PYTHON 的精華所在。
以上,
若有更好的想法歡迎提出哦!
if expression:
statements
- 如果 expression 是 True,就執行以下 statements。
- 待執行內容需要縮排(空四格或是 Tab,不可混著使用)。
elif 和 else用法:
if expression1:
statements1
elif expression2:
statements2
elif expression3:
statements3
else:
statements4
- elif 是 else 和 if 的簡寫,意思是如果還有條件為 True。
- else 是所有條件皆不成立,才會執行。
- 只有其中一個 expression 成立,執行完其 statements,即會跳出其它的 expression。
用法:
a = 1
b = 2
if a > b:
maximum = a
minimum = b
else:
maximum = b
minimum = a
print('maximum:', maximum)
print('minimum:', minimum)
n = -1
if n > 0:
print('positive')
elif n < 0:
print('negative')
else:
print('zero')
year = 2000
if year < 0:
print('illegal')
elif year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print('leap year')
else:
print('normal year')
< Loop >
loop 稱為迴圈,
分為兩種:
- while loop
- for loop
1. while loop:
while expression:
statements
# update conditions
就一直重複執行縮排內的 statements,
直到 expression 為 False 時即停止。
用法:
# 計算 0 ~ 10 總和
i = 0
sum = 0
while i <= 10:
sum += i
i += 1
print(sum) # 55
# 輾轉相除法
a, b = 18, 24
while b != 0:
a, b = b, a % b
print(a) # 6
for i in iterable:
statements
常見可迭代物件:
- range:range(start, stop, step)
for i in range(3):
print(i)
'''
0
1
2
'''
for i in range(3, 6):
print(i)
'''
3
4
5
'''
for i in range(5, 10, 3):
print(i)
'''
5
8
'''
- map:map(func, iterable),回傳一個迭代器(iterator),使用 iterable 的每個元素來計算函數。(原文:make an iterator that computes the function using arguments from each of the iterables.)。
for i in map(lambda x: x ** 2, [1, 2, 3]): # 對於 [1, 2, 3] 每個元素回傳 x ** 2
print(i)
'''
1
4
9
'''
- filter:filter(func or None, iterable),返回一個迭代器,產生 iterable 中 function(item) 為 True 的項目。如果函數為None,返回為 True 的項目。(原文:return an iterator yielding those items of iterable for which function(item) is True. If function is None, return the items that are True.)。
for i in filter(lambda x: x % 2 == 0, [1, 2, 3, 4]): # 過濾, 只取 x % 2 == 0 的元素
print(i)
'''
2
4
'''
for i in filter(None, [0, 1, 0, 2, 0]): # 過濾, 只取為 True(不為 0) 的元素
print(i)
'''
1
2
'''
- str:字串(string 學習筆記)。
- list:串列(list 學習筆記)。
- tuple。
- dict:字典(dictionary 學習筆記)。
用法:
# 九九乘法表
for i in range(1, 10):
for j in range(2, 10):
print(j, '*', i, '=', j * i, end = '\t')
print()
'''
2 * 1 = 2 3 * 1 = 3 4 * 1 = 4 5 * 1 = 5 6 * 1 = 6 7 * 1 = 7 8 * 1 = 8 9 * 1 = 9
2 * 2 = 4 3 * 2 = 6 4 * 2 = 8 5 * 2 = 10 6 * 2 = 12 7 * 2 = 14 8 * 2 = 16 9 * 2 = 18
2 * 3 = 6 3 * 3 = 9 4 * 3 = 12 5 * 3 = 15 6 * 3 = 18 7 * 3 = 21 8 * 3 = 24 9 * 3 = 27
2 * 4 = 8 3 * 4 = 12 4 * 4 = 16 5 * 4 = 20 6 * 4 = 24 7 * 4 = 28 8 * 4 = 32 9 * 4 = 36
2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 6 * 5 = 30 7 * 5 = 35 8 * 5 = 40 9 * 5 = 45
2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36 7 * 6 = 42 8 * 6 = 48 9 * 6 = 54
2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49 8 * 7 = 56 9 * 7 = 63
2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64 9 * 8 = 72
2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
'''
< Function >
在了解 function 之前,
其實我們已經先用很多 function 了。
- print()
- input()
- int(), str(), float() 等。
- sum(), min(), max(), len() 等。
其實就是有「函數名稱」、「括號(傳入參數)」,
做特定的指令並回傳數值。
然而,
還有很多好用的內建 function 可以使用。
我們也可以自己寫 function。
用法:
做特定的指令並回傳數值。
然而,
還有很多好用的內建 function 可以使用。
- abs(value):回傳 value 的絕對值。
print(abs(-2.5)) # 2.5
- bin(integer):回傳 integer 的二進位表示值。
print(bin(100)) # 0b1100100
- divmod(x, y):回傳 tuple(x // y, x % y)。
print(divmod(25, 4)) # (6, 1)
- eval(string):評估給定的 string,對於 string 做指定的指令。(原文:evaluate the given source in the context of globals and locals.)。
print(eval('1 * 2 + 3 - 4 // 2')) # 3
eval('print(100)') # 100
print(eval('len([1, 2, 3, 4, 5])')) # 5
- oct(integer):回傳 integer 代表的八進位表示值。
print(oct(100)) # 0o144
- pow(base, exp, mod):回傳 baseexp % mod。若沒有傳入 mod 參數,則回傳 baseexp。
print(pow(2, 10, 5)) # 4
print(pow(2, 10)) # 1024
- sorted(iterable, key = None, reverse = False):回傳一個排序好的 iterable 物件。可以依照喜好的 key 和是否要 reverse 排序。
print(sorted([5, 1, 3, 2, 4])) # [1, 2, 3, 4, 5]
print(sorted([5, 1, 3, 2, 4], key = lambda z: (z % 3, z))) # [3, 1, 4, 2, 5]
print(sorted([5, 1, 3, 2, 4], reverse = True)) # [5, 4, 3, 2, 1]
用法:
def add(a, b): # a, b 為傳入參數
return a + b # 回傳值
ans = add(1, 2) # 使用 function
print(ans) # 3
def add(a = 10, b = 20):
'''
預設參數 a = 10, b = 20
若沒有傳入參數就用預設參數代替
'''
return a + b # 回傳值
print(add(1, 2)) # 3
print(add(1)) # 21
print(add()) # 30
print(add(b = 0)) # 10
- 中間有預設引數但後面沒有會發生錯誤。
def add(a = 10, b, c = 20):
return a + b + c # 回傳值
# SyntaxError: non-default argument follows default argument
用起來還要注意細節,
十分麻煩。
但其實 function 對於重複性質高程式碼,
可帶來很大的便利。
def isprime(n):
if n == 2:
return True
if n % 2 == 0 or n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
print(isprime(2)) # True
print(isprime(10)) # False
冒號前面是參數,
冒號後面是回傳值。
mul = lambda a, b: a * b
print(mul(10, 20)) # 200
通常會用匿名函數表示。
# 使用 normal function
def f(z):
return (z % 3, z) # 根據 (z % 3, z) 排序
print(sorted([5, 1, 3, 2, 4], key = f)) # [3, 1, 4, 2, 5]
# 使用 lambda fuction
print(sorted([5, 1, 3, 2, 4], key = lambda z: (z % 3, z))) # [3, 1, 4, 2, 5]
< Import >
import module,
顧名思義就是導入模組,
由於簡化程式碼長度,
可以導入已經寫好的模組使用。
導入方式(以 math 為例):
import math # 直接導入, 之後使用前要加 math
import math as m # 導入名稱以 m 代入, 之後使用前要加 m
from math import * # 導入 math 所有東西, 之後直接使用
- datetime:處理基本的日期和時間類型。
import datetime
# datetime.date(year, month, day)
x = datetime.date(2020, 1, 1) # 2020 年 1 月 1 日
y = datetime.date(2020, 10, 10) # 2020 年 10 月 10 日
print((y - x).days) # 時間差幾天 # 283
print((y - x).seconds) # 0 # 沒有指定 second, 無法計算
print('----------')
# datetime.datetime(year, month, day, hour, minute, second)
x = datetime.datetime(2020, 1, 1, 1, 1, 1)
y = datetime.datetime(2020, 10, 10, 10, 10, 10)
print((y - x).days) # 時間差幾天 # 283
print((y - x).seconds) # 時間差幾秒 # 32949
- itertools:為高效循環而創建迭代器的函數。
import itertools
lst = [1, 2, 3]
# 排列
for i in itertools.permutations(lst, 2): # P 3 取 2
print(i)
'''
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
'''
print('----------')
# 組合
for i in itertools.combinations(lst, 2): # C 3 取 2
print(i)
'''
(1, 2)
(1, 3)
(2, 3)
'''
print('----------')
# 笛卡爾積
for i in itertools.product(lst, repeat = 2): # list 相乘, 重複 2 次
print(i)
'''
(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)
(2, 3)
(3, 1)
(3, 2)
(3, 3)
'''
- math:數學函數。
import math
# 常數
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print('----------')
# 三角函數(弧度量)
pi = math.pi
print(math.sin(pi)) # 1.2246467991473532e-16
print(math.cos(pi)) # -1.0
print(math.tan(pi)) # -1.2246467991473532e-16
print('----------')
# 反三角函數(弧度量)
print(math.acos(-1)) # 3.141592653589793
print(math.asin(-1)) # -1.5707963267948966
print(math.atan(-1)) # -0.7853981633974483
print('----------')
# 捨去, 進位
print(math.ceil(2.4)) # 向上取整 # 3
print(math.floor(2.4)) # 向下取整 # 2
print('----------')
# 階乘
print(math.factorial(3)) # 6
print(math.factorial(10)) # 3628800
print('----------')
# 最大公因數
print(math.gcd(18, 24)) # 6
print('----------')
# 排列, 組合
print(math.perm(5, 2)) # P 5 取 2 # 20
print(math.comb(5, 2)) # C 5 取 2 # 10
print('----------')
# 對數運算
print(math.log10(100)) # 2.0
print(math.log2(16)) # 4.0
print(math.log(10)) # 以 e 為底 # 2.302585092994046
print(math.log(27, 3)) # 以 3 為底 # 3.0
- random:生成隨機數。
import random
lst = [1, 2, 3, 4, 5]
print(random.choice(lst)) # 從 lst 隨機選取
print('----------')
print(random.choices(lst, k = 2)) # 從 lst 隨機選取 2 個, 回傳一個 list
print('----------')
print(random.randint(1, 10)) # 從 [1, 10] 隨機選取
print('----------')
print(random.randrange(1, 10, 3)) # range(1, 10, 3) 隨機選取
print('----------')
print(random.random()) # 從 [0, 1) 隨機選取小數
print('----------')
random.shuffle(lst) # 打亂 lst
print(lst)
還有很多模組要透過網路下載,
有些 OJ 並不能使用,
而這些模組就是 PYTHON 的精華所在。
以上,
若有更好的想法歡迎提出哦!
留言
張貼留言