變數是用來儲存數據的容器。在 Python 中,你可以直接為變數賦值,並且不需要明確聲明數據類型。
x = 10
name = "Alice"
is_student = True
Python 中的主要資料類別包括:
10, -3
3.14, -0.001
"Hello", 'Python'
True, False
[1, 2, 3], ["apple", "banana"]
{"name": "Alice", "age": 25}
(1, 2, 3)
age = 25
pi = 3.14159
greeting = "Hello, World!"
fruits = ["apple", "banana", "cherry"]
person = {"name": "Alice", "age": 25}
Python 支持多種運算符來進行數學運算、比較和邏輯運算。
+ : 加- : 減* : 乘/ : 除// : 整數除% : 求餘數** : 次方== : 等於!= : 不等於> : 大於< : 小於>= : 大於等於<= : 小於等於and : 並且or : 或not : 非a = 10
b = 3
# 算術運算
print(a + b) # 13
print(a / b) # 3.3333333333333335
# 比較運算
print(a > b) # True
print(a == b) # False
# 邏輯運算
print(a > 5 and b < 5) # True
print(not (a < b)) # True
Python 使用 if、elif 和 else 來進行條件判斷。
x = 15
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
在這個範例中,因為 x 的值是 15,所以會輸出 "x is greater than 10"。
>>> x is greater than 10