0% found this document useful (0 votes)
4 views

CH03 Math Function and String

PYTHON3

Uploaded by

李遠哲
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CH03 Math Function and String

PYTHON3

Uploaded by

李遠哲
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

03

數學函式、字元與字串
簡介
假設您需要估算四個城市包圍的面積。如下圖給予這四個城市相關的GPS
位置(經、緯度)。你會如何撰寫程式來解決此問題?看完本章後就可以得
到答案。

2020/3/13
2
本章綱要
➢ 利用在math模組的函式來解決數學問題(§3.2)
➢ 字串與字元的表示方式與處理(§§3.3~3.4)
➢ 使用ASCII碼和萬國碼來編碼字元(§§3.3.1~3.3.2)
➢ 使用ord函式取得字元的ASCII碼,使用chr 函式取得ASCII 碼所對應
的字元(§3.3.3)
➢ 使用轉義序列表示特殊的字元(§3.3.4)
➢ 呼叫含有end引數的print函式(§3.3.5)
➢ 使用str 函式將數字轉換為字串(§3.3.6)
2020/3/13
3
本章綱要
➢ 使用 + 運算子連結字串(§3.3.7)

➢ 從鍵盤讀取字串(§3.3.8)

➢ 介紹物件與方法(§3.5)

➢ 使用format函式將數值與字串加以格式化(§3.6)

➢ 畫不同的圖形(§3.7)

➢ 加上顏色與字型來畫圖(§3.8)

2020/3/13
4
3.2 在cmath標頭檔的三角函式
函式 描述 範例

abs(x) 回傳x的絕對值 abs(-2) 是2

max(x1, x2, …) 回傳x1, x2, …的最大值 max(1, 5, 2) 是5

min(x1, x2, …) 回傳x1, x2, …的最小值 min(1, 5, 2) 是1

pow(a, b) 回傳 ab pow(2, 3) 是8
round(5.4) 是5
回傳最接近x的整數。若與兩整數接近,
round(x) round(5.5) 是6
則回傳偶數的整數。
round(4.5) 是4

round(5.466, 2) 是5.47
round(x, n) 回傳捨位到小數點後n位的浮點數。
round(5.463, 2) 是5.46
2020/3/13
5
函式 描述 範例

fabs(x) 以浮點數回傳x的絕對值 fabs(-2) 是2.0

ceil(x) 回傳大於x的最小整數。 ceil(2.1) 是3; ceil(-2.1) 是 -2

floor(x) 回傳小於x的最大整數。 floor(2.1) 是2; floor(-2.1) 是 -3

exp(x) 回傳 ex exp(1) 是2.71828

log(x) 回傳 loge(x) log(2.71828) 是1.0

log(x,base) 回傳以指定基底的對數。 log(100, 10) 是2.0

sqrt(x) 回傳 sqrt(4.0) 是2

2020/3/13
6
函式 描述 範例

sin(x) 回傳以徑度為單位的sine三角函式 sin(3.14159 / 2) 是1; sin(3.14159) 是0

asin(x) 回傳以徑度為單位的反sine三角函式 asin(1.0) 是1.57; asin(0.5) 是0.523599

cos(x) 回傳以徑度為單位的cosine三角函式 cos(3.14159 / 2) 是0; cos(3.14159) 是 -1

acos(x) 回傳以徑度為單位的反cosine三角函式 acos(1.0) 是0; acos(0.5) 是1.0472

tan(x) 回傳以徑度為單位的tangent三角函式 tan(3.14159 / 4) 是1; tan(0.0) 是0

將x角度從徑度(radian)轉換為度數
degrees(x) degrees(1.57) 是90
(degree)

radians(x) 將x角度從度數轉換為徑度 radians(90) 是1.57

2020/3/13
7
範例程式3.1 MathFunction.py

2020/3/13
8
範例程式3.1 MathFunction.py
exp(1.0) = 2.718281828459045
log(2.78) = 1.0
log10(10,10) = 1.0
sqrt(4.0) = 2.0
sin(PI/2) = 1.0
cos(PI/2) = 6.123233995736766e-17
tan(PI/2) = 1.633123935319537e+16
degree(1.57) = 89.95437383553924
radians(90) = 1.5707963267948966

2020/3/13
9
範例程式3.2 ComputeAngles.py

➢給予三邊使用下列公式計算角度:

2020/3/13
10
範例程式3.2 ComputeAngles.py

Enter three points: 1,1,6.5,1,6.5,2.5

The three angles are 15.26 90.0 74.74


2020/3/13
11
(a) math.sqrt(4) ( j) math.floor(-2.5)
(b) math.sin(2 * math.pi) (k) round(3.5)
(c) math.cos(2 * math.pi) (l) round(-2.5)
(d) min(2, 2, 1) (m) math.fabs(2.5)
(e) math.log(math.e) (n) math.ceil(2.5)
(f ) math.exp(1) (o) math.floor(2.5)
(g) max(2, 3, 4) (p) round(-2.5)
(h) abs(-2.5) (q) round(2.6)
(i) math.ceil(-2.5) (r) round(math.fabs(-2.5))

2020/3/13
12
(a) math.sqrt(4) = 2.0 (j) math.floor(-2.5) = -3
(b) math.sin(2 * math.pi) = 0 (k) round(3.5) = 4
(c) math.cos(2 * math.pi) = 1 (l) round(-2.5) = -2
(d) min(2, 2, 1) = 1 (m) math.fabs(2.5) = 2.5
(e) math.log(math.e) = 1 (n) math.ceil(2.5) = 3
(f) math.exp(1) = 2.71 (o) math.floor(2.5) = 2
(g) max(2, 3, 4)) = 4 (p) round(-2.5) = -2
(h) abs(-2.5) = 2.5 (q) round(2.6) = 3
(i) math.ceil(-2.5) = -2 (r) round(math.fabs(-2.5)) = 2

2020/3/13
13
3.3 字串與字元
➢ 字串是一系列的字元。字串(string)是一系列的字元,而且包含文字和
數字。字串值必須以雙引號或單引號括住。Python沒有所謂的字元型
態。一個單一字元的字串表示一字元。

letter = 'A' # Same as letter = "A"


numChar = '4' # Same as numChar = "4"
message = "Good morning"
# Same as message = 'Good morning'

2020/3/13
14
警告

➢ 為了達到一致性,本書的字串是以雙引號括起的。字元或是空字串是以
單引號括起來的。這是其它語言一致性的用法,所以您可以很容易將
Python的程式轉換為其它語言。

2020/3/13
15
3.3.1 萬國碼 與 ASCII 碼
➢ Python同時也支援萬國碼(Unicode)。萬國碼是一編碼機制,用以
表示內部的字元。ASCII 是萬國碼的小小子集合。
➢ 萬國碼是由\u開頭,後接四個16進位的數字,從\u0000到\uFFFF

2020/3/13
16
範例程式3.3 DisplayUnicode.py

2020/3/13
17
附錄 B: ASCII 字元集
➢ASCII 字元集是萬國碼 \u0000 到 \u007f 的子集合。

2020/3/13
18
附錄 B: ASCII 字元集
➢ASCII 字元集是萬國碼 \u0000 到 \u007f 的子集合。

2020/3/13
19
3.3.3 ord與chr函式

>>> ch = 'a'

>>> ord(ch)

>>> 97

>>> chr(98)

>>> 'b’

>>> ord(‘A’)

>>>65
2020/3/13
20
>>> ord('a') – ord('A')
32
>>> ord('d') – ord('D')
32
>>> offset = ord('a') – ord('A')
>>> lowercaseLetter = 'h'
>>> uppercaseLetter = chr(ord(lowercaseLetter) – offset)
>>> uppercaseLetter
'H'
>>>

2020/3/13
21
3.3.4 轉義序列的特殊字元

轉義序列 名稱 ASCII碼 轉義序列 名稱 ASCII碼

\b 空白 8 \r 回到此行的前端 13

\t 跳八格 9 \\ 反斜線 92

\n 跳行 10 \' 單引號 39

\f 跳頁 12 \" 雙引號 34

2020/3/13
22
3.3.5 印出沒有換行的輸出結果

print(item, end = 'anyendingstring')

print("AAA", end = ' ')

print("BBB", end = '')

print("CCC", end = '***')

print("DDD", end = '***')

2020/3/13
23
3.3.6 str 函式

➢ str函式用來將數值轉換為字串。

>>> s = str(3.4) # Convert a float to string


>>> s
'3.4'
>>> s = str(3) # Convert an integer to string
>>> s
'3'
>>>

2020/3/13
24
3.3.7 字串連結運算子

➢您可以使用 + 運算子處理數字的相加,也可以用來連結兩個字串。

>>> message = "Welcome " + "to " + "Python"


>>> message
'Weclome to Python'
>>> chapterNo = 2
>>> s = "Chapter " + str(chapterNo)
>>> s
'Chapter 2'
>>>
2020/3/13
25
3.3.8 從控制台讀取字串

➢使用 input 方法來從控制台讀取字串。舉例來說,下述程式碼讀取從鍵


盤輸入的字串:

s1 = input("Enter a string: ")


s2 = input("Enter a string: ")
s3 = input("Enter a string: ")
print("s1 is " + s1)
print("s2 is " + s2)
print("s3 is " + s3)
2020/3/13
26
3.4 個案研究:最少的硬幣數量

➢ 假設我們想開發一個程式,將輸入的金額轉換為較小的貨幣單位。程式
讓使用者輸入浮點數型態的總金額,以美元(dollars)與分(cents)來表
示,接著輸出依序對等的美元,25分(quarters)、10分(dimes)、5分
(nickels),以及1分(pennies)的組合,以使用最少的硬幣來計算,如
範例的輸出結果所示。

2020/3/13
27
範例程式3.4:CompuuteChange.py

Enter an amount, for example, 11.56:11.56


You amount 11.56 consists of
11 dollars
2 quarters
0 dimes
1 nickels
1 pennies

2020/3/13
28
2020/3/13
29
3.5 物件與方法
➢ 在Python所有的資料(包括數值與字串)都是物件。
➢ 在Python中,數值是物件,字串是物件(object),可以說所有的資料
皆是物件。相同種類的物件擁有相同的型態(type)。您可以使用id函式
和type函式得到有關物件的資訊 。

2020/3/13
30
3.5 物件的Types 和 Ids
>>> n = 3 # n is an integer
>>> id(n)
505408904
>>> type(n)
<class ’int’>
>>> f = 3.0 # f is a float
>>> id(f) >>> s = "Welcome" # s is a string
26647120 >>> id(s)
>>> type(f)
<class ’float’> 36201472
>>> type(s)
<class ’str’>

2020/3/13
31
OOP 與 str 物件

➢ 在程式設計中,id 和 type 函式是很少被使用的,但它們是學習有關


物件的好工具。

2020/3/13
32
方法
➢ 您可以在物件中進行運算。在Python,物件的函式稱為方法
(method)。方法僅能被指定的物件所呼叫。例如,字串的型態的方法
有lower()和upper(),用以回傳一小寫或大寫的字串。

2020/3/13
33
str 物件的方法

>>> s = "Welcome"
>>> s1 = s.lower() # Invoke the lower method
>>> s1
'welcome'
>>> s2 = s.upper() # Invoke the upper method
>>> s2
'WELCOME'

2020/3/13
34
刪除前後兩端的空白字元
➢ 另一有用的方法是strip(),用來删除前、後兩端的白色空白字元。字
元 ‘ ’、\t、\f、\r,以及 \n皆為白色空白字元(whitespace
character)。 如下:

>>> s = "\t Welcome \n"

>>> s1 = s.strip() # Invoke the strip method

>>> s1

'Welcome'

2020/3/13
35
3.6 數值與字串的格式化
➢有時輸出結果需要格式化後再顯示。例如下列程式碼在給予總金額與利
率下計算利息: >>> amount = 12618.98
>>> interestRate = 0.0013
>>> interest = amount * interestRate
>>> print("Interest is", interest)
Interest is 16.404674

➢因為利息金額是貨幣,所以僅需顯示到小數點後2位。
➢可使用下述方法:format(item, format-specifier)

2020/3/13
36
>>> amount = 12618.98
>>> interestRate = 0.0013
>>> interest = amount * interestRate
>>> print("Interest is", round(interest,2))
Interest is 16.4
>>>
>>> amount = 12618.98
>>> interestRate = 0.0013
>>> interest = amount * interestRate
>>> print("Interest is",format(interest,.2f))
Interest is 16.40

2020/3/13
37
3.6.1 浮點數值的格式化

2020/3/13
38
3.6.2 科學記號的格式化

➢若將f的轉換碼改為e,此時數值將以科學記號表示。例如:

print(format(57.467657, '10.2e'))
10
print(format(0.0033923, '10.2e'))
□□5.75e+01
print(format(57.4, '10.2e')) □□3.39e-03
□□5.74e+01
print(format(57, '10.2e')) □□5.70e+01

2020/3/13
39
3.6.3 百分比的格式化

➢也可以將數值格式化為百分比,例如:

print(format(0.53457, '10.2%'))

print(format(0.0033923, '10.2%')) 10
□□□□53.46%
print(format(7.4, '10.2%'))
□□□□□0.34%
print(format(57, '10.2%')) □□□740.00%
□□5700.00%

2020/3/13
40
3.6.4 對齊的格式

➢ 數值的格式一般在預設下是向右靠齊,您可以使用 < 的格式化指定器


,將輸出結果在特定的欄位寬下向左靠齊。例如:

print(format(57.467657, '10.2f'))

print(format(57.467657, '<10.2f')) 10
□□□□□57.47
57.47

2020/3/13
41
3.6.5 整數的格式化

➢若轉換碼為d、x、o,以及b,用來將數值轉換為十進位、十六進位、
八進位,以及二進位。您可以指定。例如:

print(format(59832, '10d'))
10
print(format(59832, '<10d'))
□□□□□59832
print(format(59832, '10x')) 59832
print(format(59832, '<10x'))
□□□□□□e9b8
e9b8

2020/3/13
42
3.6.6 字串的格式化
➢您可以使用轉換碼為 s 將字串以指定的欄位寬加以格式化。例如:

print(format("Welcome to Python", '20s'))

print(format("Welcome to Python", '<20s'))

print(format("Welcome to Python", '>20s'))

20
Welcome to Python
Welcome to Python
□□□Welcome to Python 43
2020/3/13
2020/3/13
44
Checkpoint 3.19 請顯示下列敘述的輸出結果

2020/3/13
45
Checkpoint 3.20 請顯示下列敘述的輸出結果

2020/3/13
46
Checkpoint 3.21 請顯示下列敘述的輸出結果

2020/3/13
47
Checkpoint 3.22 請顯示下列敘述的輸出結果

2020/3/13
48
Checkpoint 3.23 請顯示下列敘述的輸出結果

2020/3/13
49
Checkpoint 3.24 請顯示下列敘述的輸出結果

2020/3/13
50
3.7 畫不同的形狀
➢ Python turtle的模組包含一些用以移動筆、設定筆的大小,以及放下
筆的方法
➢ 建立 turtle 物件時,其位置(position)在(0,0),此為視窗中心,其方
向設定往右直走,turtle模組使用筆來畫形狀,預設值筆是放下的

2020/3/13
51
表3.5 turtle筆畫圖狀態方法

方法 敘述

turtle.pendown() 放下筆──當移動時會做畫。

turtle.penup() 提起筆──當移動時不會做畫。

turtle.pensize() 設定筆的粗細為指定的寬度。

2020/3/13
52
表3.6 turtle移動方法
方法 敘述
turtle.forward(d) 在目前箭頭方向往前指定的距離。
turtle.backward(d) 在目前箭頭方向退後指定的距離。
turtle.right(angle) 在目前箭頭方向向右轉動指定的角度。
turtle.left(angle) 在目前箭頭方向向左轉動指定的角度。
turtle.goto(x, y) 在移動turtle到(x, y)的絕對位置。
turtle.setx(x) 在移動turtle到x軸到指定的位置。
turtle.sety(y) 在移動turtle到y軸到指定的位置。
turtle.setheading(angle) 設定的方向到指定的角度,0表示東方,90表示北方,180表示西方,270表示南方。
turtle.home() 移動turtle到原點(0, 0),其方向是東方。
turtle.circle(r, ext, step) 以指定的r、ext以及step畫圓。
turtle.dot(diameter, color) 以指定的diameter和color畫圓。
turtle.undo() 取消上一次turtle的動作。
turtle.speed(s) 設定turtle的速度,其值介於1到10之間,10表示最快的速度。 53
2020/3/13
Problem: Draw Simple Shapes

2020/3/13
54
範例程式3.5:SimpleShapes.py

2020/3/13
55
表3.7 turtle筆的顏色、填色和畫圖的方法
方法 敘述
turtle.color(c) 設定筆的顏色
turtle.fillcolor(c) 設定筆的填充顏色
turtle.begin_fill() 在填色之前呼叫此函式
turtle.end_fill() 在填色之後呼叫此函式
turtle.filling() 回傳填色狀態,Ture表示已填色,False表示未填色
turtle.clear() 清除視窗:turtle的狀態位置皆沒影響
turtle.reset() 清除視窗:turtle的狀態位置重設到原始的預設值
turtle.screensize(w,h) 設定畫布的寬與高
turtle.hideturtle() 隱藏turtle
turtle.showturtle() 顯示turtle
turtle.isvisible() 若turtle是顯現的,則回傳True

turtle.write(s,font=(“Arial”,8,”normal”)) 將字串s寫到turtle的位置,包括字型名稱、大小及型態
2020/3/13
56
範例程式3.6:ColorShapes.py

2020/3/13
57
2020/3/13
58
2020/3/13
59

You might also like