Python學習day09 - Python進階(3)

 

Python學習day09 - Python進階(3)

異常處理

1. 什麼是異常

異常其實就是咱們平時寫程序運行程序時的報錯,在Python中,異常通常分爲兩類,即語法錯誤和邏輯錯誤node

2. 語法錯誤

語法錯誤過不了python解釋器的語法檢測,因此在程序執行以前必須改正,不然程序沒法正常執行。python

常見以下例:git

 
 
 
xxxxxxxxxx
4
 
 
 
 
1
if#SyntaxError: invalid syntax
2
3
0 = 1#SyntaxError: can't assign to literal
4
 
 

語法錯誤的錯誤類型基本都是SyntaxError,後面是較詳細的描述。web

3. 邏輯錯誤

邏輯錯誤不一樣於語法錯誤的是,其錯誤類型比較多樣。好比:windows

 
 
 
xxxxxxxxxx
26
 
 
 
 
1
# TypeError:int類型不可迭代
2
for i in 3:
3
    pass
4
5
# ValueError
6
num=input(">>: ") #輸入hello
7
int(num)
8
9
# NameError
10
aaa
11
12
# IndexError
13
l=['egon','aa']
14
l[3]
15
16
# KeyError
17
dic={'name':'egon'}
18
dic['age']
19
20
# AttributeError
21
class Foo:pass
22
Foo.x
23
24
# ZeroDivisionError:沒法完成計算
25
res1=1/0
26
res2=1+'str'
 
 

 

4. 萬能捕捉異常的方式

固然咱們捕捉異常是爲了發現,並處理異常,因此這裏介紹一種萬能的捕獲異常的方法:app

 
 
 
xxxxxxxxxx
5
 
 
 
 
1
s1 = 'hello'
2
try:
3
    int(s1)
4
except Exception as e:
5
    print(e)
 
 

Exception能夠替代全部的異常類型用來賦值輸出,很是方便。而實際上如今的解釋器自己的報錯,定位錯誤的功能都挺強大的,因此用這個功能比較有限。less

Python深淺拷貝

通常Python的拷貝分爲如下三種,咱們分別介紹,用copy以前記得加上頭文件import copy.dom

1. 拷貝(賦值)

賦值的常見方式以下:ide

 
 
 
xxxxxxxxxx
7
 
 
 
 
1
lt = [1, 2, 3]
2
lt2 = lt
3
print(lt)
4
print(lt2)
5
lt.append(4)
6
print(lt)
7
print(lt2)
 
 

[1,2,3]

[1,2,3]

[1,2,3,4]

[1,2,3,4]

 
 
 
xxxxxxxxxx
1
 
 
 
 
1
上述打印結果能夠看到,lt的值變化,lt2的值也會跟着變化,這就是最通常的賦值
 
 

2. 淺拷貝

 
 
 
xxxxxxxxxx
6
 
 
 
 
1
# lt2沒有變化的狀況
2
lt = [1, 2, 3]
3
lt2 = copy.copy(lt)
4
lt.append(4)
5
print(lt)  # [1, 2, 3, 4] 
6
print(lt2)  # [1, 2, 3]
 
 

以上就是lt2沒有跟隨lt變化而變化,由於添加修改的是一個字符串,不是可變類型。

 
 
 
xxxxxxxxxx
6
 
 
 
 
1
# lt2變化的狀況
2
lt = [1, 2, 3,[4,5,6]]
3
lt2 = copy.copy(lt)
4
lt[3].append(7)
5
print(lt)  # [1, 2, 3, [4,5,6,7]] 
6
print(lt2)  # [1, 2, 3,[4,5,6]]
 
 

該例就是lt2跟隨lt變化的狀況,由於往裏面添加的是修改一個列表,是可變的類型。

3. 深拷貝

深拷貝是最穩定的拷貝,也是對原值保留最好的,永遠不會隨原值改變。

 
 
 
xxxxxxxxxx
15
 
 
 
 
1
t = [1000, 2000, 3000, [4000, 5000, 6000]]
2
print('id(lt)',id(lt))
3
print('id(lt[0])', id(lt[0]))
4
print('id(lt[1])', id(lt[1]))
5
print('id(lt[2])', id(lt[2]))
6
print('id(lt[3])', id(lt[3]))
7
print('*' * 50)
8
lt2 = copy.deepcopy(lt)
9
print('id(lt2)',id(lt2))
10
print('id(lt2[0])', id(lt2[0]))
11
print('id(lt2[1])', id(lt2[1]))
12
print('id(lt2[2])', id(lt2[2]))
13
print('id(lt2[3])', id(lt2[3]))
14
print('*' * 50)
15
 
 

由以上打印結果能夠看出,無論lt怎麼改變,lt2都不會隨之改變。

  • 總結以下:
 
 
 
xxxxxxxxxx
8
 
 
 
 
1
# 牢記: 拷貝/淺拷貝/深拷貝 只針對可變數據類型
2
3
# 拷貝: 當lt2爲lt的拷貝對象時,lt內的可變類型變化,lt2變化;lt內的不可變類型變化,lt2變化。 
4
5
#淺拷貝:當lt2爲lt的淺拷貝對象時,lt內的可變類型變化,lt2變化;lt內的不可變類型變化,lt2不變化
6
7
# 深拷貝: 當lt2爲lt的深拷貝對象時,lt內的可變類型變化,lt2不變化;lt內的不可變類型變化,lt2不變
8
 
 

基本的文件操做

什麼是文件呢,以前的博客中有介紹,文件其實就是操做系統提供給用戶的一個虛擬單位,是用來存儲數據的。那麼用Python來對文件操做有如下幾個經常使用的操做。

1. 找到文件路徑

 
 
 
xxxxxxxxxx
6
 
 
 
 
1
path = r'D:\Python學習\.idea\Python學習.iml'
2
3
# python裏就是這樣打開文件路徑的,以上這種也叫作絕對路徑。相對路徑能夠以下表示
4
path = r'Python學習.iml'
5
6
#相對路徑即你所執行的這個py文件的當前文件夾,會默認在這裏搜索
 
 

 

2. 雙擊打開

 
 
 
xxxxxxxxxx
3
 
 
 
 
1
f = open(path,'w',encoding = 'utf8')
2
print(f)
3
# r-->只讀,w-->只寫,清空當前文件後寫入,後面的encoding爲所打開文件的編碼格式
 
 

 

3. 看文件

 
 
 
xxxxxxxxxx
2
 
 
 
 
1
data = f.read()
2
print(data)
 
 

 

4. 寫文件

 
 
 
xxxxxxxxxx
1
 
 
 
 
1
f.write('fsfda')
 
 

 

5. 關閉文件

 
 
 
xxxxxxxxxx
4
 
 
 
 
1
del f 
2
f.close()
3
4
#須要注意的是,del f只是刪除了解釋器對文件的引用,並無真正關閉文件,只有f.close纔是真正的關閉文件
 
 

實戰之猜年齡遊戲

這是最近學習遇到的第一個稍有規模的代碼,實現方式有不少種,如下兩種僅供參考:

題目需求以下:

  1. 獎勵物品存放在文件price.txt
  2. 給定年齡(隨機18-60),用戶能夠猜三次年齡
  3. 年齡猜對,讓用戶選擇兩次獎勵
  4. 用戶選擇兩次獎勵後能夠退出

 

  • 常規猜年齡

     
     
     
    xxxxxxxxxx
    67
     
     
     
     
    1
    import random
    2
    3
    age = random.randint(18, 60)  # 隨機一個數字,18-60歲
    4
    count = 0  # 計數
    5
    6
    f = open('price.txt', 'r', encoding='utf8')  # price.txt右下角爲何編碼,則encoding爲何編碼
    7
    price_dict = f.read()
    8
    price_dict = eval(price_dict)  # type:dict # 獲取獎品字典
    9
    f.close()
    10
    11
    price_self = dict()
    12
    13
    while count < 3:
    14
        count += 1
    15
    16
        inp_age = input('請輸入你想要猜的年齡:')
    17
    18
        # 判斷是否爲純數字
    19
        if not inp_age.isdigit():
    20
            print('搞事就罵你傻逼')
    21
            continue
    22
    23
        inp_age = int(inp_age)
    24
    25
        # 篩選年齡範圍
    26
        if inp_age > 60 or inp_age < 18:
    27
            print('好好題目,18-60歲,非誠勿擾')
    28
            continue
    29
    30
        # 核心邏輯
    31
        if age == inp_age:
    32
            print('猜中了,請選擇你的獎品')
    33
    34
            # 打印商品
    35
            for k, v in price_dict.items():
    36
                print(f'獎品編號:{k} {v}')
    37
    38
            # 獲取獎品的兩次循環
    39
            for i in range(2):
    40
                price_choice = input('請輸入你須要的獎品編號:')
    41
    42
                if not price_choice.isdigit():
    43
                    print("恭喜你已經得到一次獎品,獎品爲空!而且請輸入正確的獎品編號!")
    44
                    continue
    45
    46
                price_choice = int(price_choice)
    47
    48
                if price_choice not in price_dict:
    49
                    print('你想多了吧!')
    50
                else:
    51
                    price_get = price_dict[price_choice]
    52
                    print(f'恭喜中獎:{price_get}')
    53
    54
                    if price_self.get(price_get):
    55
                        price_self[price_get] += 1
    56
                    else:
    57
                        price_self[price_get] = 1
    58
    59
            print(f'恭喜你得到如下獎品:{price_self}')
    60
            break
    61
    62
        elif age > inp_age:
    63
            print('猜小了')
    64
        elif age < inp_age:
    65
            print('猜大了')
    66
    67
        continue
     
     

     

  • 抽獎式猜年齡

     
     
     
    xxxxxxxxxx
    1
    74
     
     
    1
    import random
    2
    3
    age = random.randint(18, 19)  # 隨機一個數字,18-60歲
    4
    count = 0  # 計數
    5
    6
    f = open('price.txt', 'r', encoding='utf8')  # price.txt右下角爲何編碼,則encoding爲何編碼
    7
    price_dict = f.read()
    8
    price_dict = eval(price_dict)  # type:dict # 獲取獎品字典
    9
    f.close()
    10
    11
    price_self = dict()
    12
    13
    while count < 3:
    14
        count += 1
    15
    16
        inp_age = input('請輸入你想要猜的年齡:')
    17
    18
        # 判斷是否爲純數字
    19
        if not inp_age.isdigit():
    20
            print('搞事就罵你傻逼')
    21
            continue
    22
    23
        inp_age = int(inp_age)
    24
    25
        # 篩選年齡範圍
    26
        if inp_age > 60 or inp_age < 18:
    27
            print('好好題目,18-60歲,非誠勿擾')
    28
            continue
    29
    30
        # 核心邏輯
    31
        if age == inp_age:
    32
            print('猜中了,請選擇你的獎品')
    33
    34
            # 打印商品
    35
            for k, v in price_dict.items():
    36
                print(f'獎品編號:{k} {v}')
    37
    38
            # 獲取獎品的兩次循環
    39
            for i in range(2):
    40
                price_y = input(f'請按"Y or y"轉動轉盤{chr(9803)}:').lower()
    41
    42
                if price_y != 'y':
    43
                    print("恭喜你已經得到一次獎品,獎品爲空!而且請輸入'Y or y'!")
    44
                    continue
    45
    46
                #
    47
                price_choice = random.randint(0, 10000)
    48
    49
                if price_choice > 0 and price_choice < 9900:
    50
                    price_choice = 6
    51
                    print('恭喜你, 下次必定有好東西!!', end=' ')
    52
                else:
    53
                    price_choice = price_choice % 7
    54
    55
                if price_choice not in price_dict:
    56
                    print('你想多了吧!')
    57
                else:
    58
                    price_get = price_dict[price_choice]
    59
                    print(f'恭喜中獎:{price_get}')
    60
    61
                    if price_self.get(price_get):
    62
                        price_self[price_get] += 1
    63
                    else:
    64
                        price_self[price_get] = 1
    65
    66
            print(f'恭喜你得到如下獎品:{price_self}')
    67
            break
    68
    69
        elif age > inp_age:
    70
            print('猜小了')
    71
        elif age < inp_age:
    72
            print('猜大了')
     
     
    73
    74
        continue
     
     

     

以上內容均借鑑於恩師nick的博客,但願你們都去借鑑,關注,點贊~

http://www.javashuo.com/article/p-xylvnfya-gg.html

相關文章
相關標籤/搜索