1. Basic

1. Assignment

自右而左的Assignment:在幾乎所有的程式語言中,=的記號均為assignment,意是把右方演算的結果assign(指派)給左方的變數。右側的運算必然會產生一個某種變數型態的值,當把這樣的變數型態assign給左側的變數時,左側的變數便會自動被設定為該型態。x=3, y=3, x==y 若以英文表達的話,應該讀成「3 is assigned to x, 3 is assigned to y, therefore x is equal to y」。但,若以中文表達的話,則會讀成「X等於3、Y等於3、所以X等於Y」,顯然中文日常慣用的語意邏輯會較不清楚,正確地來說,應該讀成「把3指定給X、把3指定給Y,那麼若測試X是否等於Y,結果為真。」下例a = 2,那麼a就是整數的2;若是a = 2.0,那麼a就會是浮點數(floating point,也就是有小數點的)的a

a = 2 # integer
b = 3.0 # floating point number
c = '1.123' # string
d = "2" # string

a = a + b # assign a + b to a
print(a, b) # print a and b

那「等於」的符號是什麼?如果想要在程式語言中表達「相等」,通常是連續兩個等號==,例如1/2 == 4/2,為邏輯運算式,邏輯運算的結果會得到truefalse

在Python中最特別的是,Assignment的使用可以多對多,例如a, b = 1, 2

2. 變數與變數型態

intfloatlist, dictionary是python這個程式語言的內建資料型態,可參閱官方對Built-in types的說明。常見的型態有以下幾種:

  • 真偽TrueFalse

  • 數值Numeric Types— int(整數), float(有小數點的), long, complex

    • floating point number: 例如 b = 12.3

    • integer: 例如c = 123

  • 序列Sequence Types— str(文字字串), unicode, list, tuple, bytearray, buffer, xrange。

    • list: alist = []

    • tuple: ab = (1, 2, 3)

  • 集合Set Types— set, frozenset

  • 對應Mapping Types— dict。例如bdict = {1:2, 3:4, '5':6, '7':'8', 9:'10.11', 12:[13, 14, 15], 13:{14:'15', '16':[17, 18]}}

  • 檔案File Objects

變數型態的說明與定義可參閱https://docs.python.org/3.8/library/stdtypes.html。或者參考https://www.learnpython.org/en/Variables_and_Type進行練習,該練習為Datacamp的內容。

變數的命名有以下常見規則:

  • 不可用數字開始,例如123b = 13a + 14b。當然也不可以是中文。

  • 中間不得有空白,例如my book = 13a + 14b (why?)

  • 不可使用reserved word(why?)

  • 關於Python程式寫作的風格,可參考PEP 0008,其中,Naming conventions一節有提到變數要如何命名。例如:若全部是大寫的,多半是常數,例如最大寬度、PI的值;若是底線開頭的,應該是區域變數(Local variable,你還不用知道)。

Number

  • 利用Assignment(例如c = 9.0)讓該變數初始化為浮點數形態。 也可利用內建函式強制轉換型別如float(a)/b

String

  • s = ""可初始化一個string型態的變數。意即,藉此告知編譯器,s是一個string,只是暫時是空的。 若要在格式化輸出中輸出為字串,控制符號為%s

<練習1.1> 列印字串

List type: tuple and list

Mapping type: dictionary

3. 變數型態列印、偵測與轉換

3.1 型態列印

在列印輸出時,有時候我們會希望在前後多印出一些字串來說明印出來的那個結果是什麼。此時要用print formatting String print formatting。以print("my name is %s, age %s"%(name, 36.1234567))為例,其表示要將後面那兩個變數或者數值的內容,放到前面兩個%s的位置,且%s是表示,要用字串來輸出。

  • %d means printing as decimal number

  • %s means printing as string

  • %f means print as floating point number

參考資料:可以參考這篇PyFormat來了解%d.format()另外一種print formatting的寫法。也可參考以下網址的內容:https://docs.python.org/3/tutorial/inputoutput.html

# print out the following message
# Your name is  YOURNAME
# Your name is YOURNAME ! Your age is 38! 
# Your name is jilung ! You age is 38
name = "YOURNAME"
age = 38

print("Your name is ", name)
print("Your name is %s ! Your age is %s! "%(name, age))
print("Your name is %s ! You age is %s"%('jilung', 38)) 

Output:

Your name is  YOURNAME
Your name is YOURNAME ! Your age is 38! 
Your name is jilung ! You age is 38

常見錯誤:前面字串中所預留的位置和後面所欲帶入的變數/數值數量若不相同會怎樣?例如下面這個例子中,後面的arguments只有一個,前面則有兩個formatted slot。

print("Your name is %s ! You age is %s"%('jilung'))

Error message

TypeError                                 Traceback (most recent call last)
<ipython-input-6-493e0e8bd587> in <module>
----> 1 print("Your name is %s ! You age is %s"%('jilung'))

TypeError: not enough arguments for format string

3.1 偵測變數型態

type()可以用來偵測變數型態。

a, b = 1, 1.0 # integer and floating point
c, d = '1.1', "1.1" # string

# check the type of a, b, c
a, b, c = '2', 2, 2.0
print(type(a), type(b), type(c))

# check the type of d, e
d, e = [], {}
print(type(d), type(e))

3.2 變數型態轉換 Variable type converting

除了在列印的時候,可以用%d或者%f等控制字元將要列印的結果轉為某種格式以進行列印外(其機制其實是把後面要印的那些結果全部轉為字串,只是用控制符號來限制,要轉為「長什麼樣子」的字串)。我們也可以強制要求程式把某一種變數形態轉為另外一種變數形態,如以下範例。

  • float(a) -> 把a強制轉換為「浮點數」

  • str(a) -> 把a強制轉換為「字串」

  • int(a) -> 把a強制轉為整數

4. 四則運算 Arithemetic operations

加(+)、減(-)、乘(*)、除(/)、次方(**)、取餘數(%)

四則運算的計算方式和普遍數學的運算相同,由左而右,括號內先做,先乘除後加減。

  • ** - "power of."

  • % - "mod" e.g., 5%3==2, 4%2==0.

  • / - "divide" varied by data type of numberator and denominator

a, b = 10, 3

# print a and b
print("a = %d, b = %d"%(a, b))

# print the result of a/b and a%b
print("a/b=", a/b, "a/b=", a%b)

# print a/b and a%b but formatted to integer
print("a/b=%d, a%%b=%d"%(a/b, a%b))

# print a/b and a%b but formatted to float
print("a/b=%f, a%%b=%f"%(a/b, a%b))


# a divided by float(b)
print(a/float(b))

# b divides float(a)
print(float(a)/b)

# print ((a+b)**2+(a-b)**2)/float(a**2+b**2) and it result
print("((a+b)**2+(a-b)**2)/float(a**2+b**2) = ", ((a+b)**2+(a-b)**2)/float(a**2+b**2))

字串除以整數(不合法的操作)

變數型態受運算影響

變數型態會受變數所影響,如果將Integer乘上float的話,整個變數會變成float。如下面的例子中,type將會是float。

a = 3 
print(type(a * 3.0))

字串不可做四則運算

字串除以數字:如果把字串除以整數的話會產生什麼樣的情形?字串是沒辦法除以整數的,因為沒有意義,所以會產生TypeError

print(str(a)/b)
# TypeError: unsupported operand type(s) for /: 'str' and 'int'

範例一:華氏轉攝氏溫度

攝氏tc溫度等於華氏tf溫度-32後乘以5/9。

tf = 33
tc = 5.0/9.0*(tf-32)
print(tc)

<練習1.2> 攝氏轉華氏溫度

<練習1.3> 讀取鍵盤輸入

Last updated