0% found this document useful (0 votes)
5 views12 pages

Module 1 Python Basics

本文件是關於 Python 基礎的教學,涵蓋了安裝、變數、型別、串列、運算子、字串操作、條件判斷、迴圈、函式、類別、模組和字典等主題。Python 是一種直譯式語言,支持多種數據類型和操作,並且提供了豐富的內建函式和結構。文件中還提供了範例程式碼以幫助理解各個概念。

Uploaded by

王聖文
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Module 1 Python Basics

本文件是關於 Python 基礎的教學,涵蓋了安裝、變數、型別、串列、運算子、字串操作、條件判斷、迴圈、函式、類別、模組和字典等主題。Python 是一種直譯式語言,支持多種數據類型和操作,並且提供了豐富的內建函式和結構。文件中還提供了範例程式碼以幫助理解各個概念。

Uploaded by

王聖文
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

高等電腦程式設計/Python

模組一:Python 基礎
白 宏達 教授
通訊工程學系
國立臺北大學

介紹(Introduction)
Python 通常用作指令式(直譯式)語言:
它的直譯器可在多種作業系統上使用
其程式碼可透過第三方工具(例如:cx_Freeze)單獨執行
Guido van Rossum 於 1989 年 12 月開始實作 Python

Python 3.x 不相容於 Python 2.x(已不再支援)

基本安裝(Basic Installation)
前往 [Link]
點選 Downloads → 選擇 Python 3.13.3
將可執行檔儲存到某個資料夾,例如: C:/Python ,然後執行它

Anaconda
是 Python 程式語言的一個發行版,旨在簡化套件管理與部署
Anaconda

下載網址:
[Link]

包含 Jupyter Notebook(支援 Julia、Python 和 R):


提供基於網頁的互動式運算環境
VS Code
擴充套件(Extensions):Code Runner 與 Python Extension Pack
設定選項:如有需要,請設定 [Link]
建議在每台電腦上將 Python 安裝在相同的目錄中

變數與型別(Variables and Types)


不需要在使用變數前宣告,因為每個變數都是對某個物件的參考(reference)
Python 支援兩種數字型別:整數與浮點數(integers and floating point numbers)

定義一個整數的方式如下:
myInt = 7 # 建立一個整數物件
# 數值為 7,然後
# 將該物件的參考指派給 myInt

變數與型別(Variables and Types)


若要定義一個浮點數(floating point number):
myFloat = 7.0

字串(String)可以用單引號 ' 或雙引號 " 定義:


myString = 'hello'
myString = "hello"

兩者的差異在於:使用雙引號可以更容易在字串中包含撇號(apostrophes):
myString = "Don't worry about apostrophes"

變數與型別(Variables and Types)


可以對數值與字串使用簡單的運算子(operators):
one = 1
two = 2
three = one + two # 加總整數

hello = "hello"
world = "world"
helloWorld = hello + " " + world # 字串串接,結果為 "hello world"

變數與型別(Variables and Types)


可以在同一行對多個變數「同時」進行指定(assignment):
a, b = 3, 4

不支援將數字與字串混合進行運算:
# 這樣會失敗!
mixed = one + hello

串列(Lists)
建立一個串列的方法如下:
myList = [] # 建立一個空的串列
[Link](1) # 加入元素 1
[Link](2) # 加入元素 2
[Link](3) # 加入元素 3

print(myList[0]) # 輸出 1
myList[1] # 輸出 2(可能不會有作用)
myList[2] # 輸出 3

註:只有 print() 才會在程式執行時真正印出結果;單獨寫 myList[1] 在某些情況下(如非互動


式模式)不會有輸出。
基本運算子(Basic Operators)
算術運算子可用於數字:
number = 1 + 2 * 3 / 4.0 # 基本四則運算
remainder = 11 % 3 # 取餘數
squared = 7 ** 2 # 次方(7 的平方)
quotient = 7 // 2 # 整數除法

Python 支援使用加號運算子來串接字串:
helloWorld = "hello" + " " + "world"

基本運算子(Basic Operators)
Python 也支援字串的乘法運算,可用來建立重複的字串序列:
lotsOfHellos = "hello" * 10
# 會產生 'hellohellohellohellohellohellohellohellohellohello'

類似地,Python 也支援用乘法運算符來建立重複的串列:
[1, 2, 3] * 3
# 會產生 [1, 2, 3, 1, 2, 3, 1, 2, 3]

字串格式化(String Formatting)
在 Python 中建議使用 [Link]() ,取代 Python 2 的 % 運算子:
myInt = 3
myString = "list"
newString = "{} {}".format(myString, myInt)
# 結果:'list 3'

格式化指定(Format specification):
myString = "{:.2f}".format(3.14159) # 四捨五入至小數點後兩位 → '3.14'

任何非字串的物件也可以被格式化:
mylist = [1, 2, 3]
"A list: {}".format(mylist)
# 結果:'A list: [1, 2, 3]'

基本字串操作(Basic String Operations)


下列是可以對字串執行的各種操作:
aString = "Hello world!" # 定義一個字串
len(aString) # 字串長度,結果為 12
[Link]("o") # 找出第一個 'o' 的索引位置,結果為 4
[Link]("l") # 計算 'l' 出現的次數,結果為 3
aString[3:7] # 字串切片,從第 3 到第 6 個字元(不含第 7 個)
aString[-3:-1] # 倒數第 3 到倒數第 2 個字元(不含倒數第 1)
[Link]("world") # 找出 "world" 的起始位置,若找不到則傳回 -1

註: find() 會回傳子字串的最小索引,若無出現則回傳 -1 。

基本字串操作(Basic String Operations)


要建立一個全大寫或全小寫的新字串,可以使用:
[Link]() # 將所有字母轉為大寫
[Link]() # 將所有字母轉為小寫

要判斷字串是否以某段文字開頭或結尾,可以使用:
[Link]("Hello") # 檢查是否以 "Hello" 開頭
[Link]("asdfasdfasdf") # 檢查是否以指定字串結尾

基本字串操作(Basic String Operations)


要將字串拆分成一組由多個字串組成的串列(list),可使用 split() 方法:
aFewWords = [Link](' ') # 以空格為分隔符號
# 註:括號內是分隔符號(separator)

若未指定分隔符號,預設會使用任意空白字元(空格、Tab 等)進行切割:
aFewWords = [Link]() # 預設使用空白字元作為分隔

輸入與輸出(Input and Output)


從使用者輸入取得一行字串:
inputString = input()

將字串轉換為整數或浮點數:
inputN = int(inputString) # 轉為整數
inputF = float(inputString) # 轉為浮點數

在螢幕上顯示訊息:
print(inputString) # 預設會換行
print(inputN, inputF) # 一次輸出多個變數,預設以空格間隔

條件判斷(Conditions)
當一個運算式被比較或評估時,會回傳布林值 True 或 False :
x = 2

x == 2 # 輸出 True,表示相等
x == 3 # 輸出 False,因為不相等
x < 3 # 輸出 True,2 小於 3

其他比較運算子(comparison operators)還包括:
!= #不等於
> #大於
>= #大於等於
<= #小於等於
條件判斷(Conditions)
and 、 or 與 not 是布林運算子(Boolean operators),可用來建立複雜的邏輯判斷式:
name = "John"
age = 23

# 同時滿足兩個條件
if (name == "John") and (age == 23):
print("John, 23.")

# 滿足其中一個條件即可
if name == "John" or name == "Rick":
print("John or Rick.")

條件判斷(Conditions)
in運算子可用來檢查某個特定物件是否存在於可迭代的物件容器(iterable object container)中,例如
串列(list):
if name in ["John", "Rick"]:
print("John or Rick.")

Python 使用縮排(indentation)來定義程式區塊,而非使用大括號:
Python 的標準縮排為 4 個空格

Tab 或其他數量的空格也可以,只要整份程式保持一致即可

條件判斷(Conditions)
以下是使用 Python 的 if 敘述搭配程式區塊的範例:
if <條件為真>:
<執行某些動作>
....

elif <另一個條件為真>: # 相當於 else if


<執行其他動作>
....

else:
<執行最後的動作>

迴圈(Loops)
for 迴圈的用法:
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
# 依序列出串列中的每個元素

for x in range(5):
print(x)
# 輸出 0 到 4(不包含 5)

for x in range(3, 6):


print(x)
# 輸出 3 到 5(起始值為 3,終止值為 6 不包含 6)

迴圈(Loops)
while 迴圈的用法如下:
count = 0
while count < 5:
print(count)
count += 1
這段程式碼會從 0 印到 4,直到條件不成立為止。
break :用來跳出 for 或 while 迴圈

continue :用來跳過目前這一輪,直接回到 for 或 while 的下一輪判斷

迴圈(Loops)
使用 break 與 continue

count = 0
while True:
print(count)
count += 1
if count >= 5:
break

這段程式會無限迴圈,直到 count 達到 5 為止,然後透過 break 強制跳出。

for x in range(10):
if x % 2 == 0:
continue
print(x)

這段程式會跳過所有偶數,僅輸出奇數(1, 3, 5, 7, 9),因為當 x 是偶數時會被 continue 跳過 print(x) 。

函式(Functions)
在 Python 中定義函式需使用區塊關鍵字 def ,後面接函式名稱:
def MyFunction():
print("Hello From My Function!")

定義帶有參數的函式:
def MyFunctionWithArgs(name, greeting):
print("Hello, {}! {}.".format(name, greeting))

Python 提供許多內建函式(built-in functions),不需額外載入即可使用,例如:


print(), int()

類別與物件(Classes and Objects)


物件(Object)是將變數與函式封裝在一起的單一實體
物件的變數與函式是來自於類別(class)
一個 class 就是用來建立物件的模板
範例:
class MyClass:
name = "Hung-Ta"

def MyFunction(self):
print("{} in class".format([Link]))

self 是必要的參數,類似於 C++ 裡的 this ,代表該物件本身

類別與物件(Classes and Objects)


要建立一個物件 myObjectx ,並讓它屬於上面定義的 MyClass :
myObjectx = MyClass()

存取 myObjectx 中的變數:
[Link]
print([Link])
[Link] = "uh"

存取 myObjectx 中的函式:
[Link]()
模組(Modules)
在 Python 中,模組就是附檔名為 .py 的 Python 檔案,用來實作一組函式
例如: [Link] 可能包含
MyFunction() 和 MyFunctionWithArgs(name, greeting)

匯入模組需使用 import 指令
例如:
import MyModule
[Link]()

字典(Dictionaries)
字典是一種與陣列類似的資料型別,但它是透過鍵(key)和值(value)來存取,而不是使用索引
(index)
字典中每個值都可以透過對應的鍵來存取:
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781

這段程式碼建立了一個電話簿,使用名字作為鍵,電話號碼作為值。

字典(Dictionaries)
另一種方式是直接使用大括號語法來初始化字典,效果相同:
phonebook = {
"John": 938477566,
"Jack": 938377264,
"Jill": 947662781
}

這種寫法更簡潔,也更常見於實務中建立初始資料的情況。
字典(Dictionaries)
字典可以使用迴圈進行遍歷(iteration):
for name, number in [Link]():
print("{} is {}".format(name, number))

這段程式會逐一列出字典中所有的 key 與對應的 value。


若要刪除指定的鍵(key)與其對應值,可使用 del :
del phonebook["John"]

這行會從 phonebook 字典中移除 "John" 這一筆資料。

You might also like