基本型別:int, float, bool, and str
使用 type() 查詢型別。
>>> type(10)
<class 'int'>
>>> type(10/3)
<class 'float'>
>>> type(True)
<class 'bool'>
>>> type('Hello World')
<class 'str'>
和一般不同的是,bool 的值是 True 與 False,第一個字母要大寫。
使用 isinstance() 檢查型別。
tu = (1,2)
if isinstance(tu, tuple):
print('Yes! ' + str(tu) + ' is a tuple') # Yes! (1, 2) is a tuple
指定語法(建立變數)
和 Java 不同,不需要宣告變數型別,也沒有使用宣告關鍵字,直接使用新的變數名稱就可以了。
>>> hello = 'Hello World' >>> i = 10 >>> f = 3.3 >>> print(hello) Hello World >>> print(i * f) 33.0變數名稱規則:
- 可以使用英文字母、數字和底線
- 只有底線這一個特殊字元可以使用
- 長度不限
- 不可以數字開頭
- 大小寫字母都可以,區分大小寫
- 不可以使用 Python 關鍵字
刪除變數
一般並不需要刪除變數,但就是有這個語法可以使用。name = 'Neil' print(name) del name print(name) # NameError: name 'name' is not defineddel 比較常用在 list 中刪除指定 index 的 item。
Python 3 關鍵字
- True, False
- None, NaN
- and, or, not
- as
- assert
- if, elif, else, except, finally, for, in, break, continue, return, try, while
- class
- def, del, from, global, import, is, lambda, nonlocal, with, yield
- pass, raise
註解
使用井字號 # 代表該行以後的所有內容視為註解# str operator *
print('Hello'*3) # HelloHelloHello
print(3*'World') # WorldWorldWorld
型別轉換
int() 可以將各種型別的值轉成 int,如果不能轉就會丟出錯誤。- 對 float 是無條件捨去
- True 轉成 1、False 轉成 0
- 可以轉換 int 型式的字串,但無法轉換 float 型式的字串,得用 int(float(str))
>>> int('8')
8
>>> int(8.5)
8
>>> int(8)
8
>>> int(True)
1
>>> int(False)
0
>>> int('Hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello'
>>> int('8.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '8.0'
float() 可以將各種型別的值轉成 float,如果不能轉就會丟出錯誤。- True 轉成 1.0、False 轉成 0.0
>>> float(8)
8.0
>>> float(8.5)
8.5
>>> float('8.5')
8.5
>>> float(True)
1.0
>>> float(False)
0.0
>>> float('Hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'Hello'
str() 可以將各種型別的值轉成 str。- True 轉成 'True'、False 轉成 'False'
>>> str(8) '8' >>> str(8.0) '8.0' >>> str(True) 'True' >>> str(False) 'False'
char-int 轉換
# ord() & chr(),這是內建的函式,不是字串的 method
print(ord('a')) # 97
print(chr(97)) # a
自動型別轉換
Python 只會對 int、float 與 bool 進行自動型別轉換,或者說是跨型別計算。最特別也是要注意的是,不可以對 str 與其他型別進行跨型別計算,在 Java 可以使用 "Hello" + 6 得到 "Hello6",但是在 Python 會報錯。
必須明確使用 str() 或者 int() 先進行型別轉換後,才能進行計算。
>>> 5 + 1.0
6.0
>>> 5.0 + 1
6.0
>>> 1 + True
2
>>> 1.0 + False
1.0
>>> '8' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> '8' + str(2)
'82'
>>> int('8') + 2
10
算術運算子
>>> 10+2 12 >>> 10-2 8 >>> 10*2 20 >>> 10/2 5.0 >>> 10/3 3.3333333333333335 >>> 10 // 3 3 >>> 10 % 3 1 >>> 10**2 100 >>> 10^2 8+ - * / 為加減乘除。
// 為取整數,% 為取餘數。
** 為指數運算,10**2 表示 10 的二次方。
^ 為位元運算,表示 XOR,10 為 1010,2 為 10,10^2 得到 1000,即為 8。
算術運算子的優先順序如下:
- ** 指數
- * 乘、/ 除、// 取整數、% 取餘數
- + 加、- 減
增強型指定運算子
+=、-=、*=、/= 與 %= 可以用在 int 與 float 上。
另外,+= 與 *= 也可以用在 str 與 list 上。
字串運算子
字串可以使用單引號或者雙引號,沒有差別,一般是使用單引號,除非字串裡有單引號。字串串接用加號
>>> 'Hello' + ' ' + 'World' 'Hello World' >>> t = 'World' >>> 'Hello ' + t 'Hello World'另外有一個特別的字串運算子 *,用法為「字串 * 整數N」或者「整數N * 字串」,可以得到重複 N 次的字串。
>>> 'Hello'*3 'HelloHelloHello' >>> t = 'World' >>> 3*t 'WorldWorldWorld'
比較運算子 Comparison Operator
比較兩個值並回傳佈林值,有六個比較運算子:==、!=、>、>=、< 與 <=。與「自動型別轉換」一樣,int、float 與 bool 可以使用跨型別計算,但是 str 與其他型別就不可以。
只有 == 與 != 可以比較所有的 data type,其他四個只能比較 int、float 與 bool。
>>> 42 == 42.0 True >>> 42 == '42' False >>> '42' == '42' True >>> 1 == True True >>> 0 == False True >>> 1 == False Falsefloat 只是近似正確的值,直接測試 float 的相等性通常是很不可靠的。
f1 = 7 / 3 print(f1) # 2.3333333333333335 f2 = 7 * 10 / 3 f2 /= 10 # 2.333333333333333 print(f2) print(f1 == f2) # False print(abs(f1 - f2) < 0.000001) # True,要這樣比較才保險
布林運算子 Boolean Operator
三個布林運算子:and、or 與 not。運算子優先順序
- 數學運算子
- 比較運算子
- 布林運算子
>>> 2+2 == 4 and not 2+2 == 5 # 先求出數學運算 True >>> 4 == 4 and not 4 == 5 # 再求出比較運算 True >>> True and not False # 最後求出布林運算 True---
---
---
沒有留言:
張貼留言