1. 什麼是 Python?
Python 是一種簡單易學的高階程式語言,廣泛應用於網頁開發、數據分析、機器學習、自動化腳本等領域。
2. 安裝 Python
要開始學習 Python,可以前往 Python 官方網站 下載最新版本的 Python。
3. 第一個 Python 程式:Hello, World!
開始學習程式語言的經典方式是打印 “Hello, World!”。在 Python 中,我們可以這樣做:
print("Hello, World!")
4. 變數與資料型別
Python 支援多種資料型別,如數字、字串、布林值等。可以用變數來儲存這些資料。
# 數字
x = 10
y = 3.14
# 字串
name = "Alice"
# 布林值
is_student = True
# 列印變數
print(x, y, name, is_student)
5. 基本運算符
Python 支援基本的算術運算符,如加、減、乘、除。
a = 10
b = 3
# 加法
print(a + b) # 13
# 減法
print(a - b) # 7
# 乘法
print(a * b) # 30
# 除法
print(a / b) # 3.3333...
# 取餘數
print(a % b) # 1
6. 條件語句
Python 使用 if
、elif
和 else
來進行條件判斷。
age = 18
if age < 18:
print("你還未成年")
elif age == 18:
print("你剛滿 18 歲")
else:
print("你已成年")
7. 循環
Python 中有兩種主要的循環:for
和 while
。
# 使用 for 迴圈遍歷列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 使用 while 迴圈
count = 0
while count < 5:
print(count)
count += 1
8. 函數
函數是一段可重複使用的代碼,用於執行特定的任務。
# 定義一個函數
def greet(name):
print("Hello, " + name + "!")
# 調用函數
greet("Bob")
9. 列表和字典
列表和字典是 Python 中非常有用的資料結構。
# 列表
numbers = [1, 2, 3, 4, 5]
print(numbers[0]) # 1
# 字典
person = {"name": "Alice", "age": 25}
print(person["name"]) # Alice
10. 模組
Python 有很多內建的模組,可以使用 import
關鍵字來引用。
import math
# 使用 math 模組計算平方根
print(math.sqrt(16)) # 4.0