變數與資料型別#

變數 是用來儲存資料的容器。Python 採用動態型別,不需要事先宣告型別,直接賦值即可:

1
2
3
x = 10
name = "Alice"
is_active = True

變數命名規則#

  • 只能包含字母、數字、底線 _
  • 不能以數字開頭
  • 區分大小寫(ageAge 是不同變數)
  • 不能使用 Python 保留字(如 ifforclass
1
2
3
4
5
6
7
8
# 合法的變數名稱
user_name = "Bob"
score1 = 95
_private = True

# 不合法(會報錯)
# 1score = 95      # 不能以數字開頭
# my-name = "Bob"  # 不能使用連字號

多重賦值#

1
2
3
4
5
6
7
# 同時賦值給多個變數
a, b, c = 1, 2, 3
print(a, b, c)  # 1 2 3

# 多個變數指向同一個值
x = y = z = 0
print(x, y, z)  # 0 0 0

資料型別#

Python 有以下幾種基本資料型別:

型別說明範例
int整數10-50
float浮點數(小數)3.14-0.5
str字串"hello"'world'
bool布林值TrueFalse
NoneType空值None

查詢型別:type()#

1
2
3
4
5
print(type(10))       # <class 'int'>
print(type(3.14))     # <class 'float'>
print(type("hello"))  # <class 'str'>
print(type(True))     # <class 'bool'>
print(type(None))     # <class 'NoneType'>

整數(int)#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
a = 100
b = -50
c = 0

# 大數字可以用底線分隔,增加可讀性
population = 23_000_000
print(population)  # 23000000

# 不同進位制
binary = 0b1010    # 二進位,值為 10
octal = 0o12       # 八進位,值為 10
hexadecimal = 0xA  # 十六進位,值為 10

浮點數(float)#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
pi = 3.14159
temperature = -10.5

# 科學記號
speed_of_light = 3e8   # 3 × 10^8
tiny = 1.5e-4          # 0.00015

# 注意:浮點數精度問題
print(0.1 + 0.2)       # 0.30000000000000004(非精確值)
print(round(0.1 + 0.2, 1))  # 0.3(四捨五入到小數第1位)

布林值(bool)#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
is_raining = True
has_ticket = False

# 布林值實際上是整數的子類別
print(True + True)   # 2
print(True * 5)      # 5
print(False + 1)     # 1

# 哪些值等同於 False?
print(bool(0))       # False
print(bool(""))      # False(空字串)
print(bool([]))      # False(空串列)
print(bool(None))    # False

# 哪些值等同於 True?
print(bool(1))       # True
print(bool("hi"))    # True
print(bool([1, 2]))  # True

None#

None 代表「沒有值」,類似其他語言的 null

1
2
3
4
5
result = None

# 通常用 is 來判斷是否為 None
if result is None:
    print("還沒有結果")

型別轉換#

顯式轉換#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 字串轉整數
age = int("25")
print(age, type(age))  # 25 <class 'int'>

# 整數轉浮點數
price = float(100)
print(price)  # 100.0

# 數字轉字串
score = str(95)
print("分數:" + score)  # 分數:95

# 轉布林值
print(bool(0))    # False
print(bool(100))  # True

轉換失敗會報錯#

1
2
3
4
5
6
7
# 以下會產生 ValueError
# int("hello")   # 無法將非數字字串轉成整數
# int("3.14")    # 含小數點也不行,要先用 float()

# 正確做法
num = int(float("3.14"))  # 先轉 float,再轉 int
print(num)  # 3

運算符#

算術運算符#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
a = 10
b = 3

print(a + b)   # 13,加法
print(a - b)   # 7,減法
print(a * b)   # 30,乘法
print(a / b)   # 3.3333...,除法(結果為 float)
print(a // b)  # 3,整數除法(去掉小數)
print(a % b)   # 1,取餘數
print(a ** b)  # 1000,次方(10 的 3 次方)

賦值運算符#

1
2
3
4
5
6
x = 10
x += 5   # 等同於 x = x + 5,x 變成 15
x -= 3   # x = x - 3,x 變成 12
x *= 2   # x = x * 2,x 變成 24
x //= 5  # x = x // 5,x 變成 4
x **= 2  # x = x ** 2,x 變成 16

比較運算符(回傳布林值)#

1
2
3
4
5
6
7
8
a, b = 10, 5

print(a == b)  # False,等於
print(a != b)  # True,不等於
print(a > b)   # True,大於
print(a < b)   # False,小於
print(a >= 10) # True,大於等於
print(a <= 9)  # False,小於等於

邏輯運算符#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
age = 20
has_id = True

# and:兩個條件都要成立
print(age >= 18 and has_id)  # True

# or:至少一個條件成立
print(age < 18 or has_id)    # True

# not:反轉布林值
print(not has_id)            # False

input() 取得使用者輸入#

input() 讀取使用者輸入的內容, 回傳值永遠是字串

1
2
3
4
5
6
name = input("請輸入你的名字:")
print("你好," + name + "!")

# 若需要數字,要手動轉型
age = int(input("請輸入年齡:"))
print("明年你", age + 1, "歲")