簡介
Python是一種直譯式的編程語言,具有簡潔的語法和強大的函式庫支持,適用於各種應用場景,如網絡開發、數據分析、人工智能等,本節不會在基礎停太久,但也別忘了基本功扎實很重要,之後陸陸續續會上架各觀念的實際運用,所以,這些內容可以當個前導,快速熟悉一下。
一、輸入與輸出
1.1 輸出
- 句子中有單引號時,字串兩側就須使用雙引號;反之,句子中有雙引號時,字串兩側就須使用單引號。
- 可以接受多个字符串,用逗號 , 隔開。
- 將變數放入print()中,Python 會自動幫你把整數轉成字串,還會在項目之間加一個空格。
print("I'm a boy.")
print('你真的很"體貼"')
print('I am a good','boy') #依次打印字符串,遇到逗號會輸出一個空格
姓名 = "Michael"
年紀 = 20
print(姓名, "你好,我剛滿", 年紀, "歲")
1.2 輸出串接
- 中間用加號連接。
- 因為字串只能跟字串相加,所以如果放入整數int,要記得轉換型別。
- 也可以用f-string寫法,以下示範。
姓名 = Michael
年紀 = 20
print(姓名 + "你好,我剛滿" + str(年紀) "歲")
print(f"{姓名}你好,我剛滿{年紀}歲”)
1.3 多行文字輸出
- 要顯示多行文字時,兩側"""包住內容即可
print("""第一行
第二行
""")
1.4 輸入
- 透過input輸入的內容都是字串(str)
- 字串方法就是「字串附帶的小工具」,讓我們能方便地 修改、檢查或處理字串。
- 方法用「
.」來呼叫,例如.upper(),將輸入的小寫轉為大寫
正數 = int(input("請輸入數值")) #正數轉為int型態
變數 = input("請輸入數值:(a)or(b)”).upper()
print(正數, 變數)
2.變數、運算子、流程控制
2.1 變數宣告
- 變數是用來儲存數據的容器,無需明確宣告型別。
- 資料型別包括數字、字符串、布爾值等。
# 整數
a = 10
# 浮點數
b = 3.14
# 字符串
c = "Hello, Python"
# 布爾值
d = True
2.2 變數在記憶體中的表示
a=10 #找一個空間儲存10,然後把一個名字指向這個空間
b=a #把b也指向這個放10的記憶體空間
2.3 運算子
- 算術運算子:
+,-,*,/,//,%,* - 位元運算子 :
&,^,|,<<,>> - 比較運算子:
==,!=,>,<,>=,<= - 邏輯運算子:
and,or,not
# 算術運算
x = 5
y = 2
print(x + y) # 7
print(x ** y) # 25
#位元運算
a = 5 # 二進制:0101(只關注後面這幾個數字,前面都是0,取決於資料型態位元數)
b = 3 # 二進制:0011
print(a & b) # 1
print(a | b) # 7
print(a ^ b) # 6
print(a << 1) # 10
print(a >> 1) # 2
# 比較運算
print(x > y) # True
# 邏輯運算
print(x > 0 and y > 0) # True
2.4 控制流程
觀念:
- 條件語句:
if,elif,else - 循環語句:
for,while - 可以巢狀迴圈
# 條件語句:
age = 18
if age >= 18:
print("成年")
else:
print("未成年")
# while 循環
count = 0
while count < 5:
print(count) #輸出0-4
count += 1
# for 循環
for i in range(5):
print(i) #輸出0-4
3. 函式與模組
3.1 定義函式
觀念:- 使用
def關鍵字定義函式。 - 可以有參數和返回值。
範例:
def greet(name):
return (f"Hello, {name}")
print(greet("Alice")) # Hello, Alice
3.2 參數與返回值
觀念:
- 位置參數: 即按 順序 傳值,誰在前誰在後很重要,按 順序 傳值,誰在前誰在後很重要。
def greet(name, age):
print(f"你好 {name},你 {age} 歲了!")
# 使用位置參數
greet("Michael", 20)
- 關鍵字參數: 當呼叫函式時,指定參數名稱,就不用管順序。
def greet(name, age):
print(f"你好 {name},你 {age} 歲了!")
# 使用關鍵字參數
greet(age=20, name="Michael")
- 默認參數值: 如果呼叫時沒傳值,會用預設值,但如果有傳值,則會覆蓋預設值。
def power(x, n=2):
return x ** n
print(power(3)) # 9
print(power(3, 3)) # 27(3覆蓋2)
3.4 模組
觀念:
- 模組裡面放了一堆程式碼(變數、函式、類別),可以被別的程式引用,可以把模組想像成工具箱。
範例:
# 導入模組
import math
print(math.sqrt(16)) # 4.0
# 從模組中導入特定函式
from math import pi
print(pi) # 3.141592653589793
#給模組別名
import random as R
t = R.randint(1,100) #1-100之間的整數亂數值
print(t)
4. 數據結構
4.1 清單(List)
觀念:
- 可變的有序集合,可以包含不同類型的元素。
- 清單與字串之間可以透過一些語法做資料類型的轉換
- 支持索引、切片、添加、刪除等操作。
範例:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") #新增至列表(1次只能加1個)
print(fruits[3]) # orange
print(fruits[-1]) # orange
fruits.extend(["papaya", "mango"]) #新增至列表
print(fruits) # ['apple', 'banana', 'cherry', 'orange', 'papaya', 'mango']
print(fruits[1:3]) # ['banana', 'cherry'] (不包含第三位)
print(fruits[:3]) # ['apple', 'banana', 'cherry'] (0到2)
print(fruits[1:]) # ['banana', 'cherry', 'orange', 'papaya', 'mango'] (1到最後)
fruits.remove("orange") # orange 從清單消失
fruits.pop() # 預設刪掉清單最後一個項目
招呼 = "你好嗎"
print(list(招呼)) # ['你', '好', '嗎']
日期 = "2024/10/10"
print(日期.split("/")) # ['2024', '10', '10']
團體 = ["阿偉", "嘉明", "杰哥"]
print("/".join(團體)) # 阿偉/嘉明/杰哥
- 可用 in 確認資料是否在清單內(
if 預查找的資料 in 一個清單: 後面可搭配其他操作)
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("找到香蕉了!")
else:
print("清單裡沒有香蕉")
- 可用index回傳在清單中的順位 Ex : print(某一個清單.index(
預查找的資料))
fruits = ["apple", "banana", "cherry", "banana"]
print(fruits.index("banana")) # 1
4.2 元組(Tuple)
觀念:
- 不可變的有序集合。
- 適用於不可修改的數據組合。
- 元組項目操作和List一樣
範例:
coordinates = (10, 20)
print(coordinates[0]) # 10
# coordinates[0] = 15 # 會引發錯誤
4.3 字典(Dictionary)
觀念:
- 無序的鍵值對集合。
- 鍵(Key):
- 必須是不可變類型(如字符串、數字、元組)。
- 在同一字典中,鍵是唯一的,不能有重複的鍵。
- 值(Value):
- 可以是任意類型的數據(如數字、字符串、列表、字典等)。
# 創建空字典
empty_dict = {}
# 創建帶有初始值的字典
person = {"name": "Alice", "age": 25, "city": "New York"}
# 使用鍵值對參數創建
person = dict(name="Alice", age=25, city="New York")
# 使用鍵值對元組的列表創建
person = dict([("name", "Alice"), ("age", 25), ("city", "New York")])
# 訪問值
print(person["name"]) # 輸出: Alice
# 當鍵不存在時會引發 KeyError
# print(person["gender"]) # KeyError: 'gender'
# 安全地訪問值,當鍵不存在時返回默認值 None 或自定義的默認值
print(person.get("name")) # 輸出: Alice
print(person.get("gender")) # 輸出: None
print(person.get("gender", "未知")) # 輸出: 未知
# 添加新的鍵值對
person["city"] = "New York"
print(person) # {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 修改已有鍵的值
person["age"] = 26
print(person) # {'name': 'Alice', 'age': 26, 'city': 'New York'}
# 刪除指定鍵值對
del person["age"]
print(person) # {'name': 'Alice', 'city': 'New York'}
# 刪除整個字典
del person
# print(person) # NameError: name 'person' is not defined
# 移除指定鍵並返回其值
person = {"name": "Alice", "age": 25}
age = person.pop("age")
print(age) # 25
print(person) # {'name': 'Alice'}
# 當鍵不存在時,可以指定默認值
gender = person.pop("gender", "未知")
print(gender) # 未知
# 移除最後插入的鍵值對
person = {"name": "Alice", "age": 25, "city": "New York"}
item = person.popitem()
print(item) # ('city', 'New York')
print(person) # {'name': 'Alice', 'age': 25}
#遍歷鍵
person = {"name": "Alice", "age": 25}
for key in person:
print(key)
# 輸出:
# name
# age
#遍歷值
for value in person.values():
print(value)
# 輸出:
# Alice
# 25
#遍歷鍵和值
for key, value in person.items():
print(f"{key}: {value}")
# 輸出:
# name: Alice
# age: 25
#若改成下面寫法,將返回元組類型
for value in person.items():
print(value)
#清空字典中的所有元素
person.clear()
print(person) # {}
#遍歷字典的鍵值對,也可以使用 enumerate():
my_dict = {"a": 10, "b": 20, "c": 30}
for index, (key, value) in enumerate(my_dict.items(), start=1):#選擇性參數,默認值為 0。
print(f"第 {index} 個鍵值對: {key} -> {value}")
#下一章節也有示範清單配合 enumerate() 函式
4.4 集合(Set)
觀念:
- 無序不重複元素的集合。
- 支持集合運算,如並集、交集、差集。
範例:
data = {245,7,27,136,8,-1,8,-1}
#print(data[2]) #報錯,因為set是無序的
print(data) #輸出{245, 7, 136, 8, 27, -1}(無序且只有6個)
#加一個數據
data.add(9)
print(data) #輸出{9, 245, 7, 136, 8, 27, -1}
#刪掉一個數據
data.remove(9)
print(data) #輸出{245, 7, 136, 8, 27, -1}
#集合的一些操作(交集、並集、減法)
data2 = {245, 7, 27, 136, 8, -1, 10, 2, 25, 1}
print(data.intersection(data2))
#輸出交集 : {7, 136, 8, 245, 27, -1}
print(data.union(data2))
#輸出並集 : {1, 2, 7, 136, 8, 10, 25, 27, 245, -1}
print(data.difference(data2))
#輸出減法(相當於在data中卻不在data2中的數據) : set{}
data.add(13)
print(data.difference(data2))
#輸出 : {13}












