P02-Python Basic#
Objectives:
Print and print format: 介紹如何使用
print()
函數,包括格式化輸出。Print multiple objects: 使用逗號在
print()
中輸出多個變數或物件。Print with variables: 顯示變數值。
Variables and variable types: 變數的定義和類型。
Naming of variable: 變數命名規則。
Type conversion: 數據類型轉換。
Arithmetic operations: 四則運算和其他數學運算。
Example: Converting temperature format: 溫度轉換示例。
詳細內容
Comments: 註解的使用。
String: 字串的定義和操作。
Type by Assignments: 動態類型和賦值。
Using type() to check data type: 使用
type()
檢查數據類型。Converting data type: 數據類型轉換方法。
**Arithmetic operations +, -, *, , /, %: 進一步的數學運算。
print#
語法是print()
。
可用於印出字串、數字、以及變數的內容。
若是一個變數的話,會印出變數的內容;
若是一個「運算式」的話,會印出運算式的結果。
印出字串#
以下兩者是相同的,但不可以交錯使用,例如
print('hello world")
會產生Error。如果要印出雙引號,外部需要加上單引號;反之亦然。
print("hello world")
print('hello world')
print("'hello world'")
print('"hello world"')
hello world
hello world
'hello world'
"hello world"
列印計算式#
可以直接列印運算的結果,甚至像是"-"
這種文字型態資料的也可以運算,"-"*20
的意思是該符號重複20次。
print(1+2+4+5)
print("-"*20)
print((3-1)*4+5)
print(123*345-(188*123))
12
--------------------
13
19311
Print multiple terms#
「,
」在print()
中可列印數個變數或值。可以把它想像成「接下去印」的意思。
a, b, c = 1, 2, 3
print(a, b, b)
print("33", 4, c*2)
1 2 2
33 4 6
Print tab and newline#
在程式語言中,\t
代表一個tab,\n
代表使用者敲Enter下去時所產生的換行符號(Newline)。這些也可以用print()
列印出來。通常要列印\t
或\n
是為了使得印出更容易閱讀。
a, b, c = 5, 2, 3
print("a+b = ", "\t", a+b)
print("a*b = ", "\t", a*b)
print("a/b = ", "\t", a/b)
print("a%b = ", "\t", a%b)
print("a**b = ", "\t", a**b)
a+b = 7
a*b = 10
a/b = 2.5
a%b = 1
a**b = 25
Variable#
Assignment =#
**自右而左的Assignment:**在幾乎所有的程式語言中,=
的記號均為assignment,意是把右方演算的結果,Assign(指)給左方的變數。=
符號左方幾乎都是變數。且右方的資料如果是整數,Assign給左方時,左方就是個整數;如果右方資料是文字字串,Assign給左方變數,左方變數便是文字字串。
**那「等於」的符號是什麼?**如果想要在程式語言中表達「相等」,通常是連續兩個等號==
,例如1/2 == 4/2
,為邏輯運算式,邏輯運算的結果會得到true
或false
。
在Python中最特別的是,Assignment的使用可以多對多,例如a, b = 1, 2
Naming of variables#
不可用數字開始,例如
123b = 13a + 14b
。當然也不可以是中文。中間不得有空白,例如
my book = 13a + 14b
(why?)不可使用保留字(reserved word)(why?) 。因為這些保留字都是程式碼的基本語法,如果把它們拿來當變數,你的程式編輯器怎麼看得懂,這到底是一個指令,還是一個變數呢?基本保留字有這些。
and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try
關於Python程式寫作的風格,可參考PEP 0008,其中,Naming conventions一節有提到變數要如何命名。
若全部是大寫的,多半是常數,例如最大寬度、PI的值。
若是底線開頭的,應該是區域變數(Local variable,你還不用知道)
以下這些都是合法的(參考自W3School: Python Varialbe Names)
myvar = "Hsieh"
my_var = "Hsieh"
_my_var = "Hsieh"
myVar = "Hsieh"
MYVAR = "Hsieh"
myvar2 = "Hsieh"
以下這些都是不合法的變數名稱,(1) 不可以是數字開頭,(2)中間可以有_
但不可以有-
,(3)不可以有空白,不然程式不知道,這是兩個字還是一個字,(4)不可以有dot(但R是允許有dot的)
2myvar = "Hsieh" # cannot start with number
my-var = "Hsieh" # cannot have dash
my var = "Hsieh" # cannot have space
my.var = "Hsieh" # cannot have dot
Cell In[7], line 1
2myvar = "Hsieh" # cannot start with number
^
SyntaxError: invalid decimal literal
Python 內建資料型態#
list
, dictionary
是python這個程式語言的內建資料型態。請參閱5. Built-in Types。常見的資料型態共有以下幾種
基本型態
(1) 真/偽(Boolean)
只有
True
和False
兩個值。常用於條件判斷和循環控制。
如果
a=3
,然後用等號測試變數a
是否等於3時,a==3
的結果即會傳回True
。
(2) 數值型態(Numeric Types)
int
: 整數,例如a = 5
float
: 浮點數,例如b = 5.5
,粗略地來說是有小數點的數。complex
: 複數,例如c = 3 + 4j
文字型態
(3) 字串(String)
包含Unicode字符的不可變序列。
支持多種操作,如連接、切片和格式化。
用成對的雙引號或單引號括起來的為文字。例如
"test"
和'test'
其實是相同的,只是用單引號或雙引號而已,但不可以交錯使用。
容器型態
(4) 序列(Sequence Types)
list
: 有順序且可變的容器,例如[1, 2, 3]
tuple
: 有順序但不可變的容器,例如(1, 2, 3)
str
: 字串也是一種序列型態,例如"hello"
(5) 集合(Set Types)
set
: 無順序且不包含重複元素的容器,例如{1, 2, 3}
frozenset
: 不可變的集合,例如frozenset([1, 2, 3])
(6) 對應(Mapping Types)
dict
: 由鍵值對構成的無順序容器,例如{'key': 'value'}
例如
bdict = {5:2, '5':6, 12:[13, 14], 13:{14:'15', '16':[17]}}
其他
(7) 檔案對象(File Objects)
用於讀寫文件。
可以是二進位或文字模式。
"""
在下例中的`bdict`,整數`5`和字串`'5'`分別對應到兩個不同的數值。
可見是字串或文字是不可混淆的。
除此之外,數字可以拿來相除,字串是不能拿來相除的。
"""
print(True, False, 4/2==2, 5/2==2.5)
bdict = {5:2, '5':6, 12:[13, 14], 13:{14:'15', '16':[17]}}
print(bdict)
print(bdict[12])
print(bdict['5'])
print(bdict[5])
True False True True
{5: 2, '5': 6, 12: [13, 14], 13: {14: '15', '16': [17]}}
[13, 14]
6
2
print("test"=='test')
print("5"==5)
a, b, c = '2', 2, 2.0
print("if '2'==2?", a==b)
print("if 2==2.0?", b==c)
True
False
if '2'==2? False
if 2==2.0? True
String#
字串(String)是一種基本的資料型態,在Python中常用來儲存和操作文字資料。一個字串是由一系列的字符(characters)組成,這些字符可以是字母、數字、符號或其他Unicode字符。在Python中,字串可以用單引號(’)或雙引號(”)來定義,例如 ‘hello’ 或 “world”。文字字串(str
)也是一種序列型態。所以,如果有一個文字word = banana
的話,word[0]
會是b
,而word[1]
會是a
,依此類推。
但字串是不可變(immutable)的,意味著一旦它被創建,內部的內容不能被更改。例如下方程式碼my_string[3] = '1'
會產生TypeError
。然而,你可以透過各種操作來創建新的字串,例如連接(concatenation)、切片(slicing)和格式化(formatting)。
my_string = "Hello, World!"
print(my_string[0]) # 輸出 'H'
print(my_string[-1]) # 輸出 '!'
print(my_string[7:12]) # 輸出 'World'
my_string[3] = '1' # 字串不可變動 (immutability)
H
!
World
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/jirlong/Library/CloudStorage/Dropbox/Programming/pssbook/PSS/P02_0_basic.ipynb 儲存格 24 line 5
<a href='vscode-notebook-cell:/Users/jirlong/Library/CloudStorage/Dropbox/Programming/pssbook/PSS/P02_0_basic.ipynb#X66sZmlsZQ%3D%3D?line=2'>3</a> print(my_string[-1]) # 輸出 '!'
<a href='vscode-notebook-cell:/Users/jirlong/Library/CloudStorage/Dropbox/Programming/pssbook/PSS/P02_0_basic.ipynb#X66sZmlsZQ%3D%3D?line=3'>4</a> print(my_string[7:12]) # 輸出 'World'
----> <a href='vscode-notebook-cell:/Users/jirlong/Library/CloudStorage/Dropbox/Programming/pssbook/PSS/P02_0_basic.ipynb#X66sZmlsZQ%3D%3D?line=4'>5</a> my_string[3] = '1' # 字串不可變動 (immutability)
TypeError: 'str' object does not support item assignment
Defining String#
在Python中有好幾種定義字串的方式。
字串(String): 這是最基本的文字型態,使用單引號(’)或雙引號(”)來表示。例如:’hello’ 或 “world”。
多行字串: 你可以使用三個單引號(’’’)或三個雙引號(”””)來定義多行字串。
Unicode 字串: Python 3.x 以上版本中,所有的字串都是 Unicode 字串。這意味著你可以很容易地處理非英語文字。
Raw 字串: 前面加上 r 或 R,表示字串中的特殊字符將不會被轉義。
格式化字串(F-strings): 從 Python 3.6 版本開始,支援使用 F-strings 來格式化字串。
multi_line_string = """這是
一個
多行
字串 """
print(multi_line_string)
normal_string = "\n 這裡的 \n 不會被轉義"
print(normal_string)
raw_string = r"\n 這裡的 \n 不會被轉義"
print(raw_string)
name = "John"
age = 30
f_string = f"{name} is {age} years old."
print(f_string)
這是
一個
多行
字串
這裡的
不會被轉義
\n 這裡的 \n 不會被轉義
John is 30 years old.
More: Print formatting#
name = "HSIEH"
age = 42.0
print("Your name is {} ! Your age is {}".format(name, age))
print(f"Your name is {name} and age {age}")
print("Your name is {:10} and age {:10}".format(name, age))
print(f"Your name is {name:10} and age {age:10}")
Your name is HSIEH ! Your age is 42.0
Your name is HSIEH and age 42.0
Your name is HSIEH and age 42.0
Your name is HSIEH and age 42.0
table = {'Sjoerd': 41273, 'Jack': 409, 'Dcab': 7678}
for name, id in table.items():
print(f'{name:10} ==> {id:10}')
Sjoerd ==> 41273
Jack ==> 409
Dcab ==> 7678
Type by Assignments#
變數使用Assignment(指派)來讓程式知道該變數的變數型態為何。右側的運算必然會產生一個某種變數型態的值,當把這樣的變數型態assign給左側的變數時,左側的變數便會自動被設定為該型態。這種特性稱為「Dynamic Typing」。注意!一定是把右方的內容(右方可能是數值也可能是變數)指定給左方的變數。
下例把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
Using type()
to check data type#
承上節,因為在Python中,Assignment後會自動將「=」右方的變數型態Assign給左方的變數,我們可以用type()
函式來得知某個變數的變數型態。
x, y = '1.1', "1.1" # string
print(type(x), type(y))
print(type(x==y))
print(type(5/2))
print(type(4/2))
# check the type of d, e
z, w = [], {}
print(type(z))
print(type(w))
<class 'str'> <class 'str'>
<class 'bool'>
<class 'float'>
<class 'float'>
<class 'list'>
<class 'dict'>
Converting data type#
變數可以用
int()
、float()
和str()
在彼此間轉換(左側為最常用的三個)。但要注意的是,
float()
相當於是有小數點的數字,若被int()
強制轉換,會伴隨精確度的流失。例如a = int(2.3)
會只剩下2
,且沒辦法復原。如果將
integer
乘上float
的話,整個變數會變成float
。如下面的例子中,type將會是float
。
# convert a to integer, then assign to b
print(2.3, '\t', "type(2.3):", type(2.3))
print(int(2.3), '\t', 'type(int(2.3)):', type(int(2.3)))
print(str(2.3), '\t', 'type(str(2.3)):', type(str(2.3)))
a = 3
print(a, type(a))
print(a*3.0, type(a*3.0))
2.3 type(2.3): <class 'float'>
2 type(int(2.3)): <class 'int'>
2.3 type(str(2.3)): <class 'str'>
3 <class 'int'>
9.0 <class 'float'>
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(f"a = {a}, b = {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(f"a/b={a/b}, a%b={a%b}")
# print a/b and a%b but formatted to float
print(f"a/b={a/b:f}, a%b={a%b:f}")
# 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))
a = 10, b = 3
a/b= 3.3333333333333335 a/b= 1
a/b=3.3333333333333335, a%b=1
a/b=3.333333, a%b=1.000000
3.3333333333333335
3.3333333333333335
((a+b)**2+(a-b)**2)/float(a**2+b**2) = 2.0
字串除以數字:如果把字串除以整數的話會產生什麼樣的情形?字串是沒辦法除以整數的,因為沒有意義,所以會產生TypeError。
for tf in range(1, 10):
tc = (tf-32)*5/9
print(f'{tf:5} ==> {tc:-8.2f}')
1 ==> -17.22
2 ==> -16.67
3 ==> -16.11
4 ==> -15.56
5 ==> -15.00
6 ==> -14.44
7 ==> -13.89
8 ==> -13.33
9 ==> -12.78
Comments#
註解(Comments)是用來讓別人或自己後續還可以看得懂自己的程式碼的。優秀的程式設計師會把註解寫得很清楚,以利團隊合作。只要是
#
開頭的程式碼便是註解,都不會被程式所執行。