Python極簡入門:數(shù)據(jù)類型、條件語句、循環(huán)語句、異常處理
↑↑↑點(diǎn)擊上方藍(lán)字,回復(fù)資料,10個G的驚喜
一、變量、運(yùn)算符與數(shù)據(jù)類型
1. 注釋
在 Python 中,# 表示注釋,作用于整行。 ''' ''' 或者 """ """ 表示區(qū)間注釋,在三引號之間的所有內(nèi)容被注釋(多行注釋)。
2. 運(yùn)算符
1. 位運(yùn)算符
| 操作符 | 名稱 | 示例 |
|---|---|---|
| ~ | 按位取反 | ~4 |
| & | 按位與 | 4 & 5 |
| ` | 按位或 | |
| ^ | 按位異或 | 4 ^ 5 |
| << | 左移 | 4 << 2 |
| >> | 右移 | 4 >> 2 |
運(yùn)算符的優(yōu)先級
一元運(yùn)算符優(yōu)于二元運(yùn)算符。例如 3 ** -2等價于3 ** (-2)。先算術(shù)運(yùn)算,后移位運(yùn)算,最后位運(yùn)算。例如 1 << 3 + 2 & 7等價于(1 << (3 + 2)) & 7。邏輯運(yùn)算最后結(jié)合。例如 3 < 4 and 4 < 5等價于(3 < 4) and (4 < 5)。
2. 數(shù)據(jù)類型與轉(zhuǎn)換
| 類型 | 名稱 | 示例 |
|---|---|---|
| int | 整型 | |
| float | 浮點(diǎn)型 | |
| bool | 布爾型 |
通過 print() 可看出 a 的值,以及類 (class) 是int
a = 1031print(a, type(a))# 1031
type可以幫助我們?nèi)カ@取到它的類型,再通過print()打印出來。
type()不會認(rèn)為子類是一種父類類型,不考慮繼承關(guān)系。isinstance()會認(rèn)為子類是一種父類類型,考慮繼承關(guān)系如果要判斷兩個類型是否相同使用 isinstance()。
Python 里面有很多用途廣泛的包 (package),用什么你就引進(jìn)(import)什么。包也是對象,可以用dir(decimal)來看其屬性和方法
【例子】使 1/3 保留 5 位,用getcontext().prec 來調(diào)整精度。
import decimalfrom decimal import Decimaldecimal.getcontext().prec = 5c = Decimal(1) / Decimal(3)print(c)
布爾 (boolean) 型變量只能取兩個值,True 和 False。當(dāng)把布爾型變量用在數(shù)字運(yùn)算中,用 1 和 0 代表 True 和 False
類型轉(zhuǎn)換
轉(zhuǎn)換為整型 int(x, base=10)轉(zhuǎn)換為字符串 str(object='')轉(zhuǎn)換為浮點(diǎn)型 float(x)
3. print() 函數(shù)
將對象以字符串表示的方式格式化輸出到流文件對象file里。其中所有非關(guān)鍵字參數(shù)都按 str()方式進(jìn)行轉(zhuǎn)換為字符串輸出;關(guān)鍵字參數(shù) sep是實(shí)現(xiàn)分隔符,比如多個參數(shù)輸出時想要輸出中間的分隔字符;關(guān)鍵字參數(shù) end是輸出結(jié)束時的字符,默認(rèn)是換行符\n;關(guān)鍵字參數(shù) file是定義流輸出的文件,可以是標(biāo)準(zhǔn)的系統(tǒng)輸出sys.stdout,也可以重定義為別的文件;關(guān)鍵字參數(shù) flush是立即把內(nèi)容輸出到流文件,不作緩存。
沒有參數(shù)時,每次輸出后都會換行。
shoplist = ['apple', 'mango', 'carrot', 'banana']print("This is printed without 'end'and 'sep'.")for item in shoplist:print(item)# This is printed without 'end'and 'sep'.# apple# mango# carrot# banana
item值與'another string'兩個值之間用sep設(shè)置的參數(shù)&分割。由于end參數(shù)沒有設(shè)置,因此默認(rèn)是輸出解釋后換行,即end參數(shù)的默認(rèn)值為\n。
shoplist = ['apple', 'mango', 'carrot', 'banana']print("This is printed with 'sep='&''.")for item in shoplist:print(item, 'another string', sep='&')# This is printed with 'sep='&''.# apple&another string# mango&another string# carrot&another string# banana&another string
二、條件語句
1. if 語句
if 語句的 expr_true_suite代碼塊只有當(dāng)條件表達(dá)式expression結(jié)果為真時才執(zhí)行,否則將繼續(xù)執(zhí)行緊跟在該代碼塊后面的語句,如果為假則不輸出。單個 if 語句中的 expression條件表達(dá)式可以通過布爾操作符and,or和not實(shí)現(xiàn)多重條件判斷。if - else語句就是對if后的內(nèi)容進(jìn)行一個判斷,是則將繼續(xù)執(zhí)行緊跟在該代碼塊后面的語句,否則執(zhí)行else后的語句
temp = input("猜一猜小哥哥帥不帥?")guess = int(temp) # input 函數(shù)將接收的任何數(shù)據(jù)類型都默認(rèn)為 str。if guess == 帥:print("你太了解小姐姐的心思了!")print("哼,猜對也沒有獎勵!")else:print("猜錯了,小姐姐現(xiàn)在心里想的是666!")print("游戲結(jié)束,不玩兒啦!")
if - elif - else 語句對if后的內(nèi)容進(jìn)行一個判斷,是則將繼續(xù)執(zhí)行緊跟在該代碼塊后面的語句,否則繼續(xù)對elif后的內(nèi)容進(jìn)行一個判斷,是則將繼續(xù)執(zhí)行緊跟在該代碼塊后面的語句,否則直到執(zhí)行else后的語句
temp = input('請輸入成績:')source = int(temp)if 100 >= source >= 90:print('A')elif 90 > source >= 80:print('B')elif 80 > source >= 60:print('C')elif 60 > source >= 0:print('D')else:print('輸入錯誤!')
assert這個關(guān)鍵詞我們稱之為“斷言”,當(dāng)這個關(guān)鍵詞后邊的條件為 False 時,程序自動崩潰并拋出AssertionError的異常。
my_list = ['lsgogroup']my_list.pop(0)assert len(my_list) > 0# AssertionError
三、循環(huán)語句
1.while語句
while語句最基本的形式包括一個位于頂部的布爾表達(dá)式,一個或多個屬于while代碼塊的縮進(jìn)語句,代碼塊會一直循環(huán)執(zhí)行,直到布爾表達(dá)式的值為布爾假。。
string = 'abcd'while string:print(string)string = string[1:]# abcd# bcd# cd# d
如果布爾表達(dá)式不帶有<、>、==、!=、in、not in等運(yùn)算符,僅僅給出數(shù)值之類的條件,也是可以的。當(dāng)while后寫入一個非零整數(shù)時,視為真值,執(zhí)行循環(huán)體;寫入0時,視為假值,不執(zhí)行循環(huán)體。也可以寫入str、list或任何序列,長度非零則視為真值,執(zhí)行循環(huán)體;否則視為假值,不執(zhí)行循環(huán)體。
當(dāng)while循環(huán)正常執(zhí)行完的情況下,執(zhí)行else輸出,如果while循環(huán)中執(zhí)行了跳出循環(huán)的語句,比如 break,將不執(zhí)行else代碼塊的內(nèi)容。
count = 0while count < 5:print("%d is less than 5" % count)count = count + 1else:print("%d is not less than 5" % count)# 0 is less than 5# 1 is less than 5# 2 is less than 5# 3 is less than 5# 4 is less than 5# 5 is not less than 5
2.for 語句
for循環(huán)是迭代循環(huán),在Python中相當(dāng)于一個通用的序列迭代器,可以遍歷任何有序序列,如str、list、tuple等,也可以遍歷任何可迭代對象,如dict。
member = ['張三', '李四', '劉德華', '劉六', '周潤發(fā)']for each in member:print(each)# 張三# 李四# 劉德華# 劉六# 周潤發(fā)
每次循環(huán),迭代變量被設(shè)置為可迭代對象的當(dāng)前元素,提供給代碼塊使用。
當(dāng)for循環(huán)正常執(zhí)行完的情況下,執(zhí)行else輸出,如果for循環(huán)中執(zhí)行了跳出循環(huán)的語句,比如 break,將不執(zhí)行else代碼塊的內(nèi)容,與while - else語句一樣。
for num in range(10, 20): # 迭代 10 到 20 之間的數(shù)字for i in range(2, num): # 根據(jù)因子迭代if num % i == 0: # 確定第一個因子j = num / i # 計(jì)算第二個因子print('%d 等于 %d * %d' % (num, i, j))break # 跳出當(dāng)前循環(huán)else: # 循環(huán)的 else 部分print(num, '是一個質(zhì)數(shù)')# 10 等于 2 * 5# 11 是一個質(zhì)數(shù)# 12 等于 2 * 6# 13 是一個質(zhì)數(shù)# 14 等于 2 * 7# 15 等于 3 * 5# 16 等于 2 * 8# 17 是一個質(zhì)數(shù)# 18 等于 2 * 9# 19 是一個質(zhì)數(shù)
range 這個BIF的作用是生成一個從start參數(shù)的值開始到stop參數(shù)的值結(jié)束的數(shù)字序列,該序列包含start的值但不包含stop的值。
for i in range(1, 10, 2):print(i)# 1# 3# 5# 7# 9
3.跳出循環(huán)語句
break語句可以跳出當(dāng)前所在層的循環(huán)。
import randomsecret = random.randint(1, 10) #[1,10]之間的隨機(jī)數(shù)while True:temp = input("猜一猜小姐姐想的是哪個數(shù)字?")guess = int(temp)if guess > secret:print("大了,大了")else:if guess == secret:print("你太了解小姐姐的心思了!")print("哼,猜對也沒有獎勵!")breakelse:print("小了,小了")print("游戲結(jié)束,不玩兒啦!")
continue終止本輪循環(huán)并開始下一輪循環(huán)。
for i in range(10):if i % 2 != 0:print(i)continuei += 2print(i)# 2# 1# 4# 3# 6# 5# 8# 7# 10# 9
四、異常處理
1. Python 標(biāo)準(zhǔn)異常總結(jié)
| 標(biāo)識符 | 內(nèi)容 | 標(biāo)識符 | 內(nèi)容 |
|---|---|---|---|
| BaseException |
| 所有異常的 基類 | Exception | 常規(guī)異常的基類 | |
| StandardError | 所有的內(nèi)建標(biāo)準(zhǔn)異常的基類 | ArithmeticError | 所有數(shù)值計(jì)算異常的基類 |
| FloatingPointError | 浮點(diǎn)計(jì)算異常 | OverflowError | 數(shù)值運(yùn)算超出最大限制 |
| ZeroDivisionError | 除數(shù)為零 | AssertionError | 斷言語句(assert)失敗 |
| AttributeError | 嘗試訪問未知的對象屬性 | EOFError | 沒有內(nèi)建輸入,到達(dá)EOF標(biāo)記 |
| EnvironmentError | 操作系統(tǒng)異常的基類 | OError | 輸入/輸出操作失敗 |
| OSError | 操作系統(tǒng)產(chǎn)生的異常(例如打開一個不存在的文件) | WindowsError | 系統(tǒng)調(diào)用失敗 |
| ImportError | 導(dǎo)入模塊失敗的時候 | KeyboardInterrupt | 用戶中斷執(zhí)行 |
| LookupError | 無效數(shù)據(jù)查詢的基類 | IndexError | 索引超出序列的范圍 |
| KeyError | 字典中查找一個不存在的關(guān)鍵字 | MemoryError | 內(nèi)存溢出(可通過刪除對象釋放內(nèi)存) |
| NameError | 嘗試訪問一個不存在的變量 | UnboundLocalError | 訪問未初始化的本地變量 |
| ReferenceError | 弱引用試圖訪問已經(jīng)垃圾回收了的對象 | RuntimeError | 一般的運(yùn)行時異常 |
| NotImplementedError | 尚未實(shí)現(xiàn)的方法 | SyntaxError | 語法錯誤導(dǎo)致的異常 |
| IndentationError | 縮進(jìn)錯誤導(dǎo)致的異常 | TabError | Tab和空格混用 |
| SystemError | 一般的解釋器系統(tǒng)異常 | TypeError | 不同類型間的無效操作 |
| ValueError | 傳入無效的參數(shù) | UnicodeError | Unicode相關(guān)的異常 |
| UnicodeDecodeError | Unicode解碼時的異常 | UnicodeEncodeError | Unicode編碼錯誤導(dǎo)致的異常 |
| UnicodeTranslateError | Unicode轉(zhuǎn)換錯誤導(dǎo)致的異常 |
2.Python標(biāo)準(zhǔn)警告總結(jié)
| 標(biāo)識符 | 內(nèi)容 | 標(biāo)識符 | 內(nèi)容 |
|---|---|---|---|
| Warning | 警告的基類 | DeprecationWarning | 關(guān)于被棄用的特征的警告 |
| FutureWarning | 關(guān)于構(gòu)造將來語義會有改變的警告 | UserWarning | 用戶代碼生成的警告 |
| PendingDeprecationWarning | 關(guān)于特性將會被廢棄的警告 | RuntimeWarning | 可疑的運(yùn)行時行為(runtime behavior)的警告 |
| SyntaxWarning | 可疑語法的警告 | ImportWarning | 用于在導(dǎo)入模塊過程中觸發(fā)的警告 |
| UnicodeWarning | 與Unicode相關(guān)的警告 | BytesWarning | 與字節(jié)或字節(jié)碼相關(guān)的警告 |
| ResourceWarning | 與資源使用相關(guān)的警告 |
↓掃描二維碼添加好友↓ 推薦閱讀
(點(diǎn)擊標(biāo)題可跳轉(zhuǎn)閱讀)
老鐵,三連支持一下,好嗎?↓↓↓
