阿里天池Python訓練營 task 1
- 1.位運算
- 2.資料型別與轉換
- 2.1使用getcontext().prec調整精度
- 2.2isinstance(object,classinfo)
- 3.回圈陳述句
- 3.1while-else回圈
- 3.2enumerate()函式
- 4.推導式
- 4.1串列推導式
- 4.2元組推導式
- 4.3字典推導式
- 4.4集合推導式
- 4.5next()函式
- 5.例外處理
- 5.1try-except陳述句
- 5.2try-except-finally陳述句
- 5.3try-except-else陳述句
- 5.4raise陳述句
1.位運算
例:對4進行按位取反
print(bin(~4),~4)
#運行結果
-0b101 -5
計算程序:若按16位進行計算,先將4轉換成二進制:0000 0000 0000 0100,對它每一位取反得到最終結果的補碼:1111 1111 1111 1011,再根據補碼來得到原碼為:1000 0000 0000 0101,轉換為十進制就是-5,
2.資料型別與轉換
2.1使用getcontext().prec調整精度
例:使1/3保留四位,
import decimal
from decimal import Decimal
decimal.getcontext().prec=4
c=Decimal(1)/Decimal(3)
print(c)
#運行結果
0.3333
2.2isinstance(object,classinfo)
object – 實體物件,
classinfo – 可以是直接或間接類名、基本型別或者由它們組成的元組,判斷一個物件是否是為已知型別,
print(isinstance(2, int))
print(isinstance(5.7, float))
print(isinstance(True, bool))
print(isinstance('5.22', str))
#運行結果
True True True True
isinstance() 與type() 區別:
type() 不會認為子類是一種父型別別,不考慮繼承關系,
isinstance() 會認為子類是一種父型別別,考慮繼承關系,
如果要判斷兩個型別是否相同推薦使用 isinstance(),
例:
class A:
pass
class B(A):
pass
print(isinstance(A(), A)) #True
print(type(A()) == A) #True
print(isinstance(B(), A)) #True
print(type(B()) == A) #False
3.回圈陳述句
3.1while-else回圈
while 布爾運算式:
代碼塊
else:
代碼塊
當 while 回圈正常執行完的情況下,執行 else 輸出,如果 while 回圈中執行了跳出回圈的陳述句,比如 break ,將不執行 else 代碼塊的內容,
例:
count = 0
while count < 2:
print("%d is less than 2" % count)
count = count + 1
#break可直接跳出回圈,不執行else陳述句
else:
print("%d is not less than 2" % count)
# 0 is less than 2
# 1 is less than 2
# 2 is not less than 2
3.2enumerate()函式
enumerate() 函式用于將一個可遍歷的資料物件(如串列、元組或字串)組合為一個索引序列,同時列出資料和資料下標,一般用在 for 回圈當中,
enumerate(sequence, [start=0])
sequence – 一個序列、迭代器或其他支持迭代物件,
start – 下標起始位置,
例:
>>>seasons = ['Spring', 'Summer', 'Autumn', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Autumn'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # 下標從 1 開始
[(1, 'Spring'), (2, 'Summer'), (3, 'Autumn'), (4, 'Winter')]
普通的for回圈
>>>i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
print i, seq[i]
i +=1
0 one
1 two
2 three
for回圈使用enumerate()
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three
4.推導式
4.1串列推導式
串列推導式格式:
[ expr for value in collection [if condition]
例:
x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]
print(y)
#[-8, -4, 0, 4, 8]
x = [[i, j] for i in range(0, 3) for j in range(0, 3)]
print(x)
# [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]
print(a)
# [(0, 2)]
4.2元組推導式
元組推導式格式:
(expr for value in collection [if condition])
例:
a=tuple(x for x in range(10))
print(a)
#(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
4.3字典推導式
元組推導式格式:
{ key_expr: value_expr for value in collection [if condition] }
例:
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}
4.4集合推導式
元組推導式格式:
{ expr for value in collection [if condition]
例:
c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)
# {1, 2, 3, 4, 5, 6}
4.5next()函式
next() 回傳迭代器的下一個專案,
next() 函式要和生成迭代器的iter() 函式一起使用,
語法:
next(iterable[, default])
iterable – 可迭代物件
default – 可選,用于設定在沒有下一個元素時回傳該默認值,如果不設定,又沒有下一個元素則會觸發 StopIteration 例外,
例:
# 首先獲得Iterator物件:
it = iter([1, 2, 3, 4, 5])
# 回圈:
while True:
try:
# 獲得下一個值:
x = next(it)
print(x)
except StopIteration:
# 遇到StopIteration就退出回圈
break
#1 2 3 4 5
5.例外處理
5.1try-except陳述句
格式:
try:
檢測范圍
except Exception[as reason]:
出現例外后的處理代碼
作業方式:
- 首先,執行 try 子句(在關鍵字 try 和關鍵字 except 之間的陳述句
- 如果沒有例外發生,忽略 except 子句, try 子句執行后結束,
- 如果在執行 try 子句的程序中發生了例外,那么 try 子句余下的部分將被忽略,如果例外的型別和 except 之后的名稱相符,那么對應的 except 子句將被執行,最后執行 try - except 陳述句之后的代碼
- 如果一個例外沒有與任何的 except 匹配,那么這個例外將會傳遞給上層的 try 中,
例:
try:
f = open('test.txt')
print(f.read())
f.close()
except OSError:
print('打開檔案出錯')
# 打開檔案出錯
一個 try 陳述句可能包含多個 except 子句,分別來處理不同的特定的例外,最多只有一個分支會被執行,
例:
dict1 = {'a': 1, 'b': 2, 'v': 22}
try:
x = dict1['y']
except LookupError:
print('查詢錯誤')
except KeyError:
print('鍵錯誤')
else:
print(x)
# 查詢錯誤
try-except-else 陳述句嘗試查詢不在 dict 中的鍵值對,從而引發了例外,這一例外準確地說應屬 于 KeyError ,但由于 KeyError 是 LookupError 的子類,且將 LookupError 置于 KeyError 之前,因此程式 優先執行該 except 代碼塊,所以,使用多個 except 代碼塊時,必須堅持對其規范排序,要從最具針對性的例外到最通用的例外,
一個 except 子句可以同時處理多個例外,這些例外將被放在一個括號里成為一個元組,
例:
try:
...
except (OSError, TypeError, ValueError) as error:
print('出錯了!\n原因是:' + str(error))
# 出錯了!
# 原因是:unsupported operand type(s) for +: 'int' and 'str'
5.2try-except-finally陳述句
格式:
try:
檢測范圍
except Exception[as reason]:
出現例外后的處理代碼
finally:
無論如何都會被執行的代碼
不管 try 子句里面有沒有發生例外, finally 子句都會執行,
5.3try-except-else陳述句
格式:
try:
檢測范圍
except:
出現例外后的處理代碼
else:
如果沒有例外執行這塊代碼
使用 except 而不帶任何例外型別,這不是一個很好的方式,我們不能通過該程式識別出具體的例外資訊,因為它捕獲所有的例外,
5.4raise陳述句
使用 raise 陳述句拋出一個指定的例外,
例:
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
# An exception flew by!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/118060.html
標籤:其他
