6. Python-Basic
(四)Python-邏輯與比較運算
★透過邏輯與比較運算來比較兩個數值,進而得到一個布林(bool)值,而布林值的
True/False 取決於比較之後的結果.
>: 大於
<: 小於
>=: 大於等於
<=: 小於等於
==: 等於. 比較左右兩邊的數值是否相等.
!= : 不等於
not: 邏輯“否”. 如果 x 為 True, 則 not x 為 False
and: 邏輯“與”. 如果 x 為 True, 且 y 為 True, 則 x and y 為 True
or: 邏輯“或”. 如果 x、y 中至少有一個為 True, 則 x or y 為 True
In [1]: 1 > 0
Out[1]: True
In [2]: 1 < 0
Out[2]: False
In [3]: 1 >= 0
Out[3]: True
In [4]: 1 <= 0
Out[4]: False
7. Python-Basic
In [5]: 1 == 0
Out[5]: False
In [6]: 1 != 0
Out[6]: True
In [7]: not 1
Out[7]: False
In [8]: not 0
Out[8]: True
In [9]: 1 and 0
Out[9]: 0
In [10]: 1 or 0
Out[10]: 1
10. Python-Basic
(五)Python-算術與賦值運算(二)
★賦值運算是基於算術運算再加上”=”符號.
+=: 加法賦值, 將兩個數值相加的結果賦值給等號左邊的變數
-=: 減法賦值, 將兩個數值相減的結果賦值給等號左邊的變數
*=: 乘法賦值, 將兩個數值相乘或是字串被重覆顯示數次的結果賦值給等號左邊的變數
/=: 除法賦值, 將兩個數值相除的結果賦值給等號左邊的變數
//=: 取商數(整數)賦值, 將兩個數值相除並取商數賦值給等號左邊的變數
%=: 取餘數賦值, 將兩個數值相除並取餘數賦值給等號左邊的變數
**=: 指數賦值運算, 將兩個數值作指算並賦值給等號左邊的變數
In [1]: a = 5; b = 2
In [2]: a += b
In [3]: a
Out[3]: 7
In [4]: b
Out[4]: 2
11. Python-Basic
In [5]: a = 5; b = 2
In [6]: a -= b
In [7]: a
Out[7]: 3
In [8]: b
Out[8]: 2
In [9]: a = 5; b = 2
In [10]: a *= b
In [11]: a
Out[11]: 10
In [12]: b
Out[12]: 2
In [13]: a = 5; b = 2
In [14]: a /= b
In [15]: a
Out[15]: 2.5
In [16]: b
Out[16]: 2
12. Python-Basic
In [17]: a = 5; b = 2
In [18]: a //= b
In [19]: a
Out[19]: 2
In [20]: b
Out[20]: 2
In [17]: a = 5; b = 2
In [18]: a %= b
In [19]: a
Out[19]: 1
In [20]: b
Out[20]: 2
In [21]: a = 5; b = 2
In [22]: a **= b
In [23]: a
Out[23]: 25
In [24]: b
Out[24]: 2
13. Python-Basic
In [25]: str_a = 'NBA'; b = 2
In [26]: str_a *= b
In [27]: str_a
Out[27]: NBANBA
In [28]: b
Out[28]: 2
14. Python-Basic
(六)Python-位元運算
★位元運算就是將數字轉成二進制來進行運算
&: 將兩個二進制數值作“與”的運算
|: 將兩個二進制數值作“或”的運算
^: 將兩個二進制數值作“互斥或”的運算
~: 將二進制數值作“反”的運算
<<: 將二進制數值作“左移”的運算
>>: 將二進制數值作“右移”的運算
In [1]: numa = 20; numb = 19
In [2]: bin(numa)
Out[2]: '0b10100'
In [3]: bin(numb)
Out[3]: '0b10011'
In [4]: bin(numa & numb)
Out[4]: '0b10000'
In [5]: bin(numa | numb)
Out[5]: '0b10111'
In [6]: bin(numa ^ numb)
Out[6]: '0b111'
17. Python-Basic
In [1]: num1 = 1; num2 = 3
In [2]: if num1 > num2:
print("num1 > num2")
if num1 < num2:
print("num1 < num2")
num1 < num2
In [3]: if num1 > num2:
print("num1 > num2")
elif num1 < num2:
print("num1 < num2")
else:
print("num1 = num2")
num1 < num2
18. Python-Basic
(八)Python-循環語句
★循環語句可以使用 for 或 while 來重覆做一作事情,當給定的判斷條件成立時,將執行循環
語句,直到退出循環語句.在撰寫循環語句時需與條件語句一樣要注意這兩點,1.循環式後面
要有冒號(:),2.執行的語句要縮排.
語法 1: for,使用串列(mylist)作為控制條件,並以串列裡的元素做循環輸出.
NumList = [num_1, num_2, num_3]
for var in NumList:
print(var)
語法 2: for,使用 range(num1,num2,num3)作為控制條件,並以 range 中的參數做循環
輸出. Num3 為每次循環增減的數字(default=1).如果 num3 為正數,則循環起始值為 num1,
最終值為 num2-1;如果 num3 為負數,則循環起始值為 num1,最終值為 num2+1。
for var in range(num1,num2,num3):
print(var)
語法 3: while
var = num1
while 判斷條件(True):
執行語句
19. Python-Basic
In [1]: NumList = [1,2,3,4,5]
In [2]: for i in NumList:
print(i)
1
2
3
4
5
In [1]: for i in range(0,5,1):
print(i)
0
1
2
3
4
32. Python-Basic
介紹如何查詢 tuples 的元素、連接和刪除等操作.
[查詢]首先要知道每個元素的對應位置的索引,第一個元素的位置索引為 0,依序加 1.直到最
後一個元素,並將要查詢的位置索引放在中括號內即可查詢到相對應的元素.
In [1]: tup = ('Year:', 2019, 'Month:', 2, 'Day:', 4)
In [2]: print(tup)
('Year:', 2019, 'Month:', 2, 'Day:', 4)
In [3]: print(tup[0],'-',tup[1],'-',tup[2],'-',tup[3],'-',tup[4],'-',tup[5])
Year: - 2019 - Month: - 2 - Day: - 4
[連接]使用+可將多個 tuples 連接在一起.
In [1]: tup = ()
In [2]: tup_year = ('Year:', 2019)
In [3]: tup_month = ('Month:', 2)
In [4]: tup_day = ('Day:', 4)
In [5]: tup = tup_year + tup_month + tup_day
In [6]: print(tup)
('Year:', 2019, 'Month:', 2, 'Day:', 4)
33. Python-Basic
[刪除]無法使用 del 刪除 tuples 中的某一個元素.
In [1]: tup = ('Year:', 2019, 'Month:', 2, 'Day:', 4)
In [2]: print(tup)
('Year:', 2019, 'Month:', 2, 'Day:', 4)
In [3]: del tup[1]
Traceback (most recent call last):
File "<ipython-input-144-20024ba0e7cc>", line 3, in <module>
del tup[1]
TypeError: 'tuple' object doesn't support item deletion
使用 del 刪除整個 tuples.
In [1]: tup = ('Year:', 2019, 'Month:', 2, 'Day:', 4)
In [2]: print(tup)
('Year:', 2019, 'Month:', 2, 'Day:', 4)
In [3]: del tup
In [4]: print(tup)
Traceback (most recent call last):
File "<ipython-input-147-8130c03e2c82>", line 1, in <module>
print(tup)
NameError: name 'tup' is not defined
35. Python-Basic
介紹如何查詢 dictionaries 的元素、取代、加入和刪除等操作.
[查詢]如果要查詢 key 所對應的 value,只要變數加中括號,並在括號中輸入 key,就可以查
詢到對應的值.
In [1]: Temp_dict = {'Year':2019 , 'Month':2 , 'Day':4}
In [2]: print(Temp_dict)
{'Year': 2019, 'Month': 2, 'Day': 4}
In [3]: print(Temp_dict['Year'])
2019
In [4]: print(Temp_dict['Month'])
2
In [5]: print(Temp_dict['Day'])
4
36. Python-Basic
[取代]定義在 dict 中的 key 是不能被修改取代,只有 value 可以被修改取代. 另外,key:
value 是可以被新增在已經定義的 dict 中.
In [1]: Temp_dict = {'Year':2019 , 'Month':2 , 'Day':4}
In [2]: Temp_dict['Year'] = 2018
In [3]: Temp_dict['Month'] = 12
In [4]: Temp_dict['Day'] = 31
In [5]: print(Temp_dict)
{'Year': 2018, 'Month': 12, 'Day': 31}
In [1]: Temp_dict = {'Year':2019 , 'Month':2 , 'Day':4}
In [2]: Temp_dict['Time(hr)'] = 10
In [3]: Temp_dict['Time(min)'] = 20
In [4]: Temp_dict['Time(sec)'] = 36
In [5]: print(Temp_dict)
{'Year': 2019, 'Month': 2, 'Day': 4, 'Time(hr)': 10, 'Time(min)': 20, 'Time(sec)':
36}
37. Python-Basic
[刪除]del 可以對整個字典或對字典一組 key:value 作刪除;clear 只能清空整個字典無法
只對一組 key:value 作清空.
In [1]: Temp_dict = {'Year':2019 , 'Month':2 , 'Day':4}
In [2]: del Temp_dict['Year']
In [3]: print(Temp_dict)
{'Month': 2, 'Day': 4}
In [4]: del Temp_dict
In [5]: print(Temp_dict)
Traceback (most recent call last):
File "<ipython-input-156-f800888ee7c8>", line 1, in <module>
print(Temp_dict)
NameError: name 'Temp_dict' is not defined
In [1]: Temp_dict = {'Year':2019 , 'Month':2 , 'Day':4}
In [2]: Temp_dict.clear()
In [3]: print(Temp_dict)
{}
40. Python-Basic
(十二)Python- 類別 class
★Class 類別,就如同一個模具,可以一直套用這個模具去生產相同屬性但不同參數的物件,
就可以反覆使用這個類別產生無限個物件.使用上很簡單,類別程式是以 class 關鍵字再接物
件名稱(首字使用大寫).舉節日作為例子,每個節日都有相同的屬性,但有不同的參數.例如:
節日都有自己名字的屬性,每個節日對應到名字屬性都有一個特殊的參數(日期),第一個節日
的名字為新年, 第二個節日的名字為青年節, 第三個節日的名字為清明節,那麼就以節日作為
第一個類別.
範例一.建立一個 Festival 類別, 包含名字一個屬性,以及一個方法(_init_).其
中,_init_:初始化類別的動作. self:表示建立的類別. name:指的是屬性
In [1]: class Festival ():
def __init__(self, name):
self.name = name
In [2]: num1_festival = Festival("New Year's Day")
In [3]: print("1st festival: ",num1_festival.name)
1st festival: New Year's Day
41. Python-Basic
範例二.建立一個 Festival_date 類別,包含名字和日期兩個屬性,以及一個方法(_init_).
其中,_init_:初始化類別的動作. self:表示建立的類別. name:指的是名字屬性. date:
指的是日期屬性。
In [1]: class Festival_date ():
def __init__(self, name, date):
self.name = name
self.date = date
In [1]: num1_festival_date = Festival_date("New Year's Day", "Jan. 1")
In [2]: num2_festival_date = Festival_date("Youth Day", "Mar. 29")
In [3]: num3_festival_date = Festival_date("Tomb Sweeping Day", "Apr. 5")
In [4]: print("1st festival_date: ",num1_festival_date.name ,"-",
num1_festival_date.date)
1st festival_date: New Year's Day - Jan. 1
In [5]: print("2nd festival_date: ",num2_festival_date.name ,"-",
num2_festival_date.date)
2nd festival_date: Youth Day - Mar. 29
In [6]: print("3th festival_date: ",num3_festival_date.name ,"-",
num3_festival_date.date)
3th festival_date: Tomb Sweeping Day - Apr. 5
42. Python-Basic
範例三.建立一個 Personal,包含身高和體重兩個屬性,以及三個方法分別為(_init_)、飲
水建議值和 BMI 值.其中,_init_:初始化類別的動作. self:表示建立的類別. height:
指的是身高屬性. weight: 指的是體重屬性
In [1]: class Personal ():
def __init__(self, height, weight):
self.height = height
self.weight = weight
def Drink_Water(self):
return (self.weight * 40)
def BMI(self):
return (self.weight / ((self.height*0.01)**2))
In [2]: Benson = Personal(174,78)
In [3]: print('Drink Water', Benson.Drink_Water(),' cc')
Drink Water 3120 cc
In [4]: print('BMI=', Benson.BMI())
BMI= 25.762980578676178
44. Python-Basic
範例一.Write
In [1]: Write_data = open('python_file.txt', 'w')
In [2]: Write_data.write ("Python is a programming language.")
Out[2]: 33
In [3]: Write_data.write ("Python can be used on a server to create web
applications.")
Out[3]: 58
In [4]: Write_data.close()
範例二.Read
In [1]: Read_data = open('python_file.txt', 'r')
In [2]: Read_data.read()
Out[2]: 'Python is a programming language.Python can be used on a server to create
web applications.'
In [3]: Read_data.readline()
Out[3]: 'Python is a programming language.Python can be used on a server to create
web applications.'
In [4]: Read_data.readlines()
Out[4]: ['Python is a programming language.Python can be used on a server to
create web applications.']