python基礎篇實戰

HanZeSon發表於2018-12-07

1. 判斷下面的結果

# 1. 判斷下面的結果
# 1 > 1 or 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6
print(1 > 1 or 3 < 4 or ((4 > 5 and 2 > 1) and 9 > 8) or 7 < 6)
# True
# 1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8 and 4 > 6 or 3 < 2
print((1 > 2 and 3 < 4) or (4 > 5 and 2 > 1) or (9 < 8 and 4 > 6) or 3 < 2)
# False
# not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8 and 4 > 6 or 3 < 2
print(((not 2 > 1) and 3 < 4) or (4 > 5 and 2 > 1) or (9 < 8 and 4 > 6) or 3 < 2)
# False
解題答案

2.求出下列邏輯語句的值

# 2.求出下列邏輯語句的值
# (1) 8 or 3 and 4 or 2 and 0 or 9 and 7
print(8 or (3 and 4) or (2 and 0) or (9 and 7))
# 結果是 8
# (2) 0 or 2 and 3 and 4 or 6 and 0 or 3
print((0 or (((2 and 3) and 4) or ((6 and 0) or 3))))
# 結果是 4
# (3) 5 and 9 or 10 and 2 or 3 and 5 or 4 or 5
print(((5 and 9) or ((10 and 2) or ((3 and 5) or (4 or 5)))))
# 結果為9
解題答案

3. 下列結果是什麼?

# 3. 下列結果是什麼?
# (1)6 or 2 > 1 結果為6
# (2)3 or 2 > 1 結果為3
# (3)0 or 5 < 4 結果為False
# (4)5 < 4 or 3 結果為3
# (5)2 > 1 or 6 結果為True
# (6)3 and 2 > 1 結果為True
# (7)0 and 3 > 1 結果為0
# (8)2 > 1 and 3 結果為3
# (9)3 > 1 and 0 結果為0
# (10)3 > 1 and 2 or 2 < 3 and 3 and 4 or 3 > 2 結果為2
解題答案

4.計算1 - 2 + 3...+99中除了88以外所有數的總和?

# 6. 計算1 - 2 + 3...+99中除了88以外所有數的總和?
i = 1
sum = 0
while i < 100:
    if i == 88:
        i += 1
        continue
    elif i % 2 == 0:
        sum -= i
    else:
        sum += i
    i += 1
print(sum)
View Code

5.計算1 - 2 + 3...-99中除了88以外所有數的總和?

# 計算1 - 2 + 3...-99中除了88以外所有數的總和?
i = 0
j = -1
sum = 0
while i < 99:
    i += 1
    if i == 88:
        continue
    else:
        j = -j
        sum += i*j
print(sum)
解題答案

6.使用者登入(三次輸錯機會)且每次輸錯誤時顯示剩餘錯誤次數

i = 3
username = "hanzeson"
password = "123456"
while i > 0:
    name = input("請輸入使用者名稱:")
    passwd = input("請輸入密碼:")
    i -= 1
    if name == username and passwd == password:
        print("""
        恭喜您登陸成功
        你的賬號:%s
        您的密碼:%s
        """ % (name,passwd))
        break
    else:
        if i == 0:
            print("您的次數已經用完了")
        print("你還有" + str(i) +"次機會")
        print("您的使用者和密碼無效")
解題答案
i = 3
username = "hanzeson"
password = "123456"
while i > 0:
    name = input("請輸入使用者名稱:")
    i -= 1
    if name == username:
        passwd = input("請輸入密碼:")
        if passwd == password:
            print("""
            恭喜您登陸成功
            你的賬號:%s
            您的密碼:%s
            """ % (name,passwd))
            break
        else:
            if i == 0:
                print("您的次數已經用完了")
                answer = input("再試試? /Y")
                if answer.lower() == "y":
                    i = 3
            print("你還有" + str(i) + "次機會")
            print("您的密碼輸入錯誤")
    else:
        if i == 0:
            print("您的次數已經用完了")
            answer = input("再試試? /Y")
            if answer.lower() == "y":
                i = 3
        print("你還有" + str(i) +"次機會")
        print("您的使用者名稱輸入錯誤")
print("要不要臉,記不住就別試了")
升級版

7.考試題

# Python基礎資料型別考試題
# 考試時間:兩個半小時     滿分100分(80分以上包含80分及格)
# 一,基礎題。
# 1,    簡述變數命名規範(3分)

    # 1、變數由字母、數字、下劃線任意組成
    # 2、不能以數字開頭
    # 3、不能使用python關鍵字
    # 4、變數要具有可描述性
    # 5、變數不能是中文
    # 5、官網推薦駱峰體和下劃線,這裡推薦下劃線
# 2,位元組和位的關係。(2分)

    # 1位元組 = 8位
# 3,’太白’使用utf-8編碼時,佔的位數和位元組數,是多少?使用gbk編碼時,佔的位數
# 和位元組數,是多少。(2分)

     # 太白      utf-8    位數:48           位元組:6
     #         gbk         位數:32       位元組:4
# 4,默寫字串的十二個功能,並描述其作用。(12分)
#     1、capitalize()  首字母大寫
#     2、upper()   字串全部大寫
#     3、lower()   字串全部小寫
#     4、format()  格式化輸出
#     5、strip()   去字串左右空格,tab,換行符
#     6、replace() 字串替換
#     7、lstrip()   去字串左邊空格,tab,換行符
#     8、rstrip()  去字串右邊邊空格,tab,換行符
#     9、startswith()  檢測字串是否是相同的開頭,結果是True,False
#     10、endswith()   檢測字串是否是相同的結尾,結果是True,False
#     11、swapcase()   字串大小寫翻轉
#     12、title()  字串每個由非字母隔開的單詞首字母大寫
#     13、isdigit()    是否全部是數字
#     14、isalpha()    是否全部是字母
#     15、isalnum()    是否數字字母組成
#     16、count()  個數
#     17、center()  居中,可以填寫填充物

# 5,數字,字串,列表,元祖,字典對應的布林值的False分別是什麼?(5分)

    # 數字:0
    # 字串:空字串
    # 列表:空列表
    # 元組:空元組
    # 字典:空字典

# 6,書寫Python2與python3中的三個不同。(3分)

    # python2:程式碼混亂、冗餘     ASCII   互動:raw_input()
    # python3:程式碼簡明、優美     UTF-8   互動:input()

# 7,寫程式碼,有如下列表,利用切片實現每一個功能(每題一分,共計4分)
# li = [1,3,2,’a’,4,’b’,5,’c’]
# 1)通過對li列表的切片形成新的列表l3,l3 = [’1,2,4,5]
# 2)通過對li列表的切片形成新的列表l4,l4 = [3,’a’,’b’]
# 3)通過對li列表的切片形成新的列表l5,l5 = [‘c’]
# 4)通過對li列表的切片形成新的列表l6,l6 = [‘b’,’a’,3]

    # 1
    # l3 = li[::2]
    # 2
    # l4 = li[1:-2:2]
    # 3
    # l5 = li[-1:]
    # 4
    # l6 = li[-3::-2]

# 8,組合巢狀題。
# a,寫程式碼,有如下列表,按照要求實現每一個功能(每題3分,寫出一種方法得1分,寫出兩種方法的3分。此題共9分)
# (每個都是一行程式碼實現)
# lis = [[‘k’,[‘qwe’,20,{‘k1’:[‘tt’,3,’1’]},89],’ab’]]
# 1)將列表lis中的’tt’變成大寫(用兩種方式)。
# 2)將列表中的數字3變成字串’100’(用兩種方式)。
# 3)將列表中的字串’1’變成數字101(用兩種方式)。

    # 1
    # lis[0][1][2]['k1'][0] = lis[0][1][2]['k1'][0].upper()
    # lis[0][1][2]['k1'][0] = 'TT'
    # 2
    # lis[0][1][2]['k1'][1] = str(lis[0][1][2]['k1'][1] + 97)
    # lis[0][1][2]['k1'][1] = '100'
    # 3
    # lis[0][1][2]['k1'][2] = 101
    # lis[0][1][2]['k1'][2] = int( '10' + lis[0][1][2]['k1'][2])

# b,寫程式碼,有如下字典,按照要求實現每一個功能(5分)
# dic = {‘k1’:’v1’,’k2’:[‘alex’,’sb’],(1,2,3,4,5):{‘k3’:[‘2’,100,’wer’]}}
# 1)將’k2’對應的值的最後面新增一個元素’23’。
# 2)將’k2’對應的值的第一個位置插入一個元素’a’。
# 3)將(1,2,3,4,5)對應的值新增一個鍵值對’k4’,’v4’。
# 4)將(1,2,3,4,5)對應的值新增一個鍵值對(1,2,3),’ok’。
# 5)將’k3’對應的值的’wer’更改為’qq’。

#     # 1
#     dic = {'k1':'v1','k2':['alex','sb'],(1,2,3,4,5):{'k3':['2',100,'wer']}}
#     dic['k2'].append('23')
#     # 2
#     dic['k2'].insert(0,'a')
#     # 3
#     dic[(1,2,3,4,5)]['k4'] = 'v4'
#     # 4
#     dic[(1,2,3,4,5)][(1,2,3)] = 'ok'
#     # 5
#     dic[(1,2,3,4,5)]['k3'][2] = 'qq'

# 9,轉化題(4分)。
#
# Int與str之間如何轉化,轉換的結果是什麼?有沒有條件?

#int加''變成str  str必須是數字才能轉化為int

# Int 與 bool之間如何轉化,轉換的結果是什麼?有沒有條件?

# False---->int  0    True---->int 1
# 非0即為真,0為假

# str 與 bool之間如何轉化,轉換的結果是什麼?有沒有條件?

#空字串轉化為bool值為False  其他為True

# str 與 list 能否轉化?如何轉化?

#能轉化,用split

# 10,實現下列結果(5分)。
# 1)有列表li = [‘alex’,’wusir’,’rain’]通過操作該列表構造一個字串s=’alexwusirrain’
# 2)有列表li = [‘alex’,’wusir’,’rain’]通過操作該列表構造一個字串s=’alex*wusir*rain’
# 3)有字串s = ‘alexwusirlex’,通過操作該字串構造一個列表li = [‘a’,’exwusirlex’]
# 4)有字串s = ‘alex wusir’,通過操作該字串構造一個列表li = [‘alex’,’wusir’]
# 5)有字串s = ‘alex’通過操作該字串構造一個字串s1 = ‘a_l_e_x’
li = ['alex','wusir','rain']
# 1
s = li[0]+li[1]+li[2]
# 2
s = '*'.join(li)
# 3
li = s.split("l",1)
# 4
li = s.split(' ')
# 5
s1 = '_'.join(s)

# 11,分別使用while迴圈,和for迴圈列印1-2+3-4+5.......+99的結果。(10分)

#     第一種
i = 1
summ = 0
while i < 100:
    if i % 2 == 0:
        summ -= i
    else:
        summ += i
    i += 1
print(summ)
#       第二種
summ = 0
for i in range(1,100):
    if i % 2 == 0:
        summ -= i
    else:
        summ += i
print(summ)


# 12,使用range列印100,99,98,....1,0(2分)

    # for i in range(100,-1,-1):
    #     print(i)

# 13,計算使用者輸入內容中索引為奇數並且對應的元素為數字的個數(沒有則個數為零)(6分)

count =0
num_input = input('請輸入內容:')
for i,v in enumerate(num_input):
    if i % 2 == 1 and v.isdigit():
        count += 1
print(count)


# 14,補充程式碼(從已有的程式碼下面繼續寫):(6分)
# 有如下值li= [11,22,33,44,55,77,88,99,90],將所有大於 66 的值儲存至字典的第一個key中,將小於 66 的值儲存至第二個key的值中。
# li = [11,22,33,44,55,77,88,99,90]
# result = {}
# for row in li:
# ......

li = [11,22,33,44,55,77,88,99,90]
result = {}
for row in li:
    result.setdefault('k1',[])
    result.setdefault('k2',[])
    if row > 66:
        result['k1'].append(row)
    elif row < 66:
        result['k2'].append(row)
print(result)

# 15,查詢列表li中的元素,移除每個元素的空格,並找出以’A’或者’a’開頭,並以’c’結尾的所有元素,並新增到一個新列表中,最後迴圈列印這個新列表。(3分)
# li = [‘taibai ’,’alexC’,’AbC ’,’egon’,’ Ritian’,’ Wusir’,’  aqc’]

li = ['taibai ','alexC','AbC ','egon',' Ritian',' Wusir','  aqc']
l1 = []
for i in li:
    i = i.strip()
    if i.upper().startswith('A') and i.endswith('c'):
        l1.append(i)
print(l1)


# 16,實現一個整數加法計算器:(3分)
# 如:content = input(‘請輸入內容:’)  # 如使用者輸入:5+8+7....(最少輸入兩個數相加),然後進行分割再進行計算,將最後的計算結果新增到此字典中(替換None):
# dic={‘最終計算結果’:None}。

content = input('請輸入內容:')
dic = {'最終計算結果':None}
sum = 0
str = content.split('+')
for i in str:
    sum = sum + int(i)
    dic['最終計算結果'] = sum
print(dic)

# 17,按要求完成下列轉化(如果按照索引去做,只能得4分)。(6分)
# list3 = [
#     {"name": "alex", "hobby": "抽菸"},
#     {"name": "alex", "hobby": "喝酒"},
#     {"name": "alex", "hobby": "燙頭"},
#     {"name": "alex", "hobby": "Massage"},
#     {"name": "wusir", "hobby": "喊麥"},
#     {"name": "wusir", "hobby": "街舞"},
# ]
# # 如何把上面的列表轉換成下方的列表?
# list4 = [
#     {"name": "alex", "hobby_list": ["抽菸", "喝酒", "燙頭", "Massage"]},
#     {"name": "wusir", "hobby_list": ["喊麥", "街舞"]},
# ]

list3 = [
    {"name": "alex", "hobby": "抽菸"},
    {"name": "alex", "hobby": "喝酒"},
    {"name": "alex", "hobby": "燙頭"},
    {"name": "alex", "hobby": "Massage"},
    {"name": "wusir", "hobby": "喊麥"},
    {"name": "wusir", "hobby": "街舞"},
]
list4 = []
list4.append({})
list4.append({})
list5 = []
list6 = []
dic = {}
for i in list3:
    if i["name"] == "alex":
        for j in i.values():
            if j != 'alex':
                list5.append(j)
    elif i["name"] == "wusir":
        for k in i.values():
            if k != 'wusir':
                list6.append(k)
list4[0].setdefault("name","alex")
list4[0].setdefault("hobby_list",list5)
list4[1].setdefault("name","wusir")
list4[1].setdefault("hobby_list",list6)
print(list4)

# 18,寫程式:模擬公司hr錄入員工賬號密碼的程式。(10分)
# 1),員工的賬號密碼儲存在這種資料型別中:
# user_list = [
#     {'username':'barry','password':'1234'},
#     {'username':'alex','password':'asdf'},
#     .........
#              ]
# 2)非法字元模板:board = ['張三','李小四','王二麻子']
# 3)Hr輸入使用者名稱,密碼(可持續輸入,如果想終止程式,那就在輸入使用者名稱時輸入Q或者q退出程式),在Hr輸入使用者名稱時,檢測此使用者名稱是否有board裡面的非法字元,如果有非法字元,則將非法字元替換成同數量的*(如王二麻子替換成****),然後新增到user_list中,如果沒有非法字元,則直接新增到user_list中,每次新增成功後,列印出剛新增的使用者名稱,密碼。

user_list = []
t = 0
board = ['張三','李小四','王二麻子']
flag = True
while flag:
    name = input("請輸入姓名:退出請按Q/q").strip()
    if name.upper() == 'Q':
        flag = False
    else:
        passwd = input("請輸入密碼")
        for i in board:
            if i in name:
                name = name.replace(i,len(i)*'*')
        print(name,passwd)
        user_list.append({})
        user_list[t]['username'] = name
        user_list[t]['password'] = passwd
        t += 1
print(user_list)
習題和答案

8.寫一個購物車

功能要求:
要求使用者輸入總資產,例如:2000
顯示商品列表,讓使用者根據序號選擇商品,加入購物車
購買,如果商品總額大於總資產,提示賬戶餘額不足,否則,購買成功。
goods = [{"name": "電腦", "price": 1999},
           {"name": "滑鼠", "price": 10},
      {"name": "遊艇", "price": 20},
      {"name": "美女", "price": 998},
shop = [
    ['iphone8',5000],
    ['kndle',988],
    ['ps4 pro',2800],
    ['psv',1200],
    ['mp3',100]
]
shop_car = []
saving = input("請輸入預算:")
if saving.isdigit():
    saving=int(saving)

while True:
    for i,v in enumerate(shop,1):
        print(i,"-",v)
    choice = input("請選擇商品編碼到購物車:[確認:q]")
    if choice.isdigit():
        choice=int(choice)
        if choice > 0 and choice<=len(shop):
            p_item = shop[choice-1]
            if p_item[1]<saving:
                saving -= p_item[1]
                shop_car.append(p_item)
                print("您選購的商品%s,剩餘%s" % (p_item,saving))
            else:
                print("您的餘額不足,剩餘%s" % saving)
    elif choice=="q":
        print("----您的購物車清單----")
        for i in shop_car:
            print(i)
        guess = input("是否確認購買:q/n")
        if guess == "q":
            print("您已經購買%s,餘額%s" % (shop_car,saving))
            break
        else:
            print("歡迎再來")
        break
    else:
        print("輸入編碼無效")
else:
    print('輸入金錢無效')
簡單版
money = input("請輸入預算:")
if money.isdigit():
    money=int(money)
shop = [['1','iphone8',5888],['2','kndle',988],['3','ps4 pro',2800],['4','psv',1200],
        ['5','psvtv',450],['6','ps4 controler',230],['7','mp3',100]]
i = 1#為了通過修改i 退出多重迴圈
allChoice = []
while(i):
    for num in range(len(shop)):  # 列印商品列表
        print(str(shop[num][0]).ljust(5), shop[num][1].ljust(20), str(shop[num][2]).ljust(10), )
    choice = input("請輸入要加入購物車的商品編號:")
    choice = [int(it) for it in choice.split(' ')]
    allChoice += choice #choice是單次選擇的商品列表,allchoice是所有選擇的商品列表
    while(1):
        total = 0
        choiceSet = set(allChoice)#轉換成集合,便於不重複計數
        for it in choiceSet:
            print(shop[it-1][0],shop[it-1][1],shop[it-1][2],'*',allChoice.count(it))
            total += shop[it-1][2]*allChoice.count(it)
        print("總計:",total,"餘額:",money-total)
        print("---------------------------------\n"
            "1:繼續選購 2:整理購物車 3:結算\n")
        option = int(input( "請選擇:"))
        if option == 1:
            break
        elif option == 2:
            item_num = int(input("請輸入要刪除的商品"))
            allChoice.remove(item_num)#每次只會刪除一個元素
            continue
        else:
            if money>=total:
                print("購物結束,餘額為:",money-total)
            else:
                print("餘額不足,還差金額:",total-money)
            i = 0
            break#整個退出
    else:
        print('輸入的編號錯誤')
else:
    print("輸入的金錢錯誤")
大神版
while True:
    money = input("請輸入總資產:").strip()
    if money.isdigit():
        break
    else:print("\033[1;31;43m總資產輸入錯誤,請重新輸入\033[0m")
money = int(money)
money1 =money
buy = []
goods = [{"name": "電腦", "price": 1999},
           {"name": "滑鼠", "price": 10},
         {"name": "遊艇", "price": 20},
         {"name": "美女", "price": 998},
]
pr = "price"
na = "name"
while True:
    print("請選擇如下商品".center(50,"*"))
    for i,j in enumerate(goods,1):
        print("編號{}\t\t商品名稱:{}\t\t商品價格{}".format(i,j[na],j[pr]))
    print("*"*55)
    number = input("請輸入要買商品的編號(充值請按\033[0;31mC/c\033[0m,刪除請按\033[0;31mD/d\033[0m,退出請按\033[0;31mQ/q\033[0m):").strip()
    if number.isdigit():
        number = int(number)
        if number <= len(goods):
            if goods[number-1][pr] <= money:
                buy.append(goods[number-1])
                money -= goods[number-1][pr]
                print("已經新增購物車 \033[0;31m%s\033[0m ,剩餘總資產 \033[0;31m%d\033[0m" % (goods[number-1][na],money))
            else:print("\033[1;31;43m賬戶餘額不足\033[0m")
        else:print("\033[1;31;43m編號超出範圍\033[0m")
    elif number.upper() == "Q":
        if buy:
            print("您購買的商品有:")
            for k in buy:
                print(k[na])
            print("總消費 \033[0;31m%d\033[0m" % (money1-money))
        else:
            print("\033[1;31;43m您購物車為空\033[0m")
        break
    elif number.upper() == "C":
        while True:
            money2 = input("請輸入充值金額:")
            if money2.isdigit():
                money2 = int(money2)
                money += money2
                print("充值成功,剩餘總資產 \033[0;31m%d\033[0m" % money)
                break
            else:print("\033[1;31;43m充值金額不合法\033[0m")
    elif number.upper() == "D":
        if buy:
            print("購物車商品".center(50, "*"))
            for l,m in enumerate(buy,1):
                print("編號{}\t\t商品名稱:{}\t\t商品價格{}".format(l,m[na],m[pr]))
            print("*"*55)
            delate = input("請輸出要刪除商品的編號").strip()
            if delate.isdigit():
                delate = int(delate)
                if delate <= len(buy):
                    del buy[delate-1]
                    print("\033[1;31;43m已刪除成功\033[0m")
                else:print("\033[1;31;43m輸出的編號超出範圍\033[0m")
            else:print("\033[1;31;43m輸出的編號不合法\033[0m")
        else:print("\033[1;31;43m購物車為空\033[0m")
    else:print("\033[1;31;43m輸出的引數錯誤\033[0m")
升級版

9.程式: 三級選單

要求: 

  1. 列印省、市、縣三級選單
  2. 可返回上一級
  3. 可隨時退出程式
city = {
    "北京":{
        "朝陽":{
            "國貿":{
                "CICC":{},
                "HP":{},
                "渣打銀行":{},
                "CCTV":{},
            },
            "望京":{
                "陌陌":{},
                "賓士":{},
                "360":{},
            },
            "三里屯":{
                "優衣庫":{},
                "apple":{},
            },
        },
        "昌平":{
        "沙河":{
            "老男孩":{},
            "阿泰包子":{},
        },
        "天通苑":{
            "鏈家":{},
            "我愛我家":{},
        },
        "回龍觀":{},
    },
        "海淀":{
        "五道口":{
            "谷歌":{},
            "網易":{},
            "sohu":{},
            "sogou":{},
            "快手":{},
        },
        "中關村":{
            "騰訊":{},
            "百度":{},
            "youku":{},
        },},
    },
    "上海":{
        "黃埔":{
            "人民廣場":{},
            "上海美術館":{},
            "上海博物館":{},
        },
        "徐匯":{
            "觀象臺":{},
            "桂林公園":{},
        },
        "長寧":{
            "上海動物園":{},
            "宋慶齡陵園":{},
        },
        },
    "山東":{
        "濟南":{
            "平陰縣":{},
            "商河縣":{},
        },
        "青島":{
            "市南區":{},
            "嶗山區":{},
        },
    },
}

current_layer = city
parent_layers = []
while True:
    for key in current_layer:
        print(key)
    choice = input("輸入城市>>[返回:b,退出:q]:")
    if len(choice) == 0:continue
    if choice in current_layer:
        parent_layers.append(current_layer)
        current_layer = current_layer[choice]
    elif choice == "b":
        if parent_layers:
            current_layer = parent_layers.pop() # 取出列表的最後一個值
    elif choice == "q":
        break
    else:
        print("已經最後一層了無法再繼續")
簡單版
menu = {"河北省":{"石家莊":["新華區","橋西區橋東區","長安區"],
                    "唐山市":["路北區","路南區","古冶區"],
                    "秦皇島市":["海港區","山海關區","盧龍縣"]},
        "江蘇":{"南京市":["玄武區","下關區","六合區","溧水縣"],
                "無錫市":["崇安區","北塘區","南長區","錫山區"]
              }
        }
flag = True
menu_list1 = list(menu.keys())
address_list = []
while flag:
    for i,j in enumerate(menu_list1,1):
        print(i,j)
    address_input = input("請輸入要查詢的編號,退出請按Q/q").strip()
    if address_input.isdigit():
        address_input = int(address_input)
        if address_input <= len(menu_list1):
            while flag:
                addree_number1 = menu_list1[address_input-1]
                menu_list2 = list(menu[addree_number1].keys())
                for k,l in enumerate(menu_list2,1):
                    print(k,l)
                address2_input = input("請輸入要查詢的編號,返回請按B/b,退出請按Q/q").strip()
                if address2_input.isdigit():
                    address2_input = int(address2_input)
                    if address2_input <= len(menu_list2):
                        while flag:
                            addree_number2 = menu_list2[address2_input-1]
                            for m,n in enumerate(menu[addree_number1][addree_number2],1):
                                print(m,n)
                            addree3_input = input("返回請按B/b,退出請按Q/q")
                            if addree3_input.upper() == 'B':
                                break
                            elif addree3_input.upper() == 'Q':
                                flag = False
                            else:print("輸入不合法")
                    else:print("輸入編號超出範圍")
                elif address2_input.upper() == 'B':
                    break
                elif address2_input.upper() == 'Q':
                    flag = False
                else:print("輸入不合法")
        else:print("輸入編號超出範圍")
    elif address_input.upper() == 'Q':
        break
    else:print("輸入不合法")
升級版

10.程式: 登入註冊

要求: 

  1. 登入限制三次
  2. 註冊寫入到文字中
  3. 登入從文字中讀取
  4. 匹配登入成功,不匹配繼續登入
print("歡迎登入son工作室".center(50,"*"))
num = 0
flag = True
lis = []
while flag:
    choice = input("登入請按1,註冊請按2")
    if choice == "1":
        while flag:
            username = input("請輸入使用者名稱:")
            password = input("請輸入密碼:")
            num += 1
            with open("login", mode="r+", encoding="utf-8") as f2:
                for line in f2:
                    lis.append(line)
                    if username in line and password in line:
                        print("恭喜您登入成功".center(40,"*"))
                        print("""您的使用者名稱%s
                            您的密碼%s""".strip() % (username,password))
                        flag = False
                    else:
                        print("您的使用者名稱和密碼輸入錯誤")
                        sb = input("您已經%s次登入,退出q,繼續請按任意鍵"% num)
                        if sb.upper() == "Q":flag = False
    elif choice == "2":
        rag_user = input("請輸入你要註冊使用者名稱:")
        rag_pass = input("請輸入你要註冊密碼:")
        with open("login", mode="w+", encoding="utf-8") as f1:
            if rag_user not in f1 and rag_pass not in f1:
                f1.write("{}/t{}".format(rag_user,rag_pass))
                print("恭喜您註冊成功!")
                print("""您的註冊賬號%s
                    您的註冊密碼%s""".strip() % (rag_user,rag_pass))
                flag = True
View Code
# 實現效果:
# 從info.txt檔案中讀取員工及其工資資訊,最後將修改或增加的員工工資資訊也寫入原info.txt檔案。
# 效果演示:
# 1. 查詢員工工資
# 2. 修改員工工資
# 3. 增加新員工記錄
# 4. 退出
import sys
with open("info.txt","r",encoding="utf-8") as f: # 開啟info.txt
    file = list(f) # 將讀到的f轉換為一個列表
    msg = '''
    1.查詢員工工資
    2.修改員工工資
    3.增加新員工記錄
    4.退出
    '''# 使用者操作選單
exit_flag = False  # 標註退出程式的標記位
while not exit_flag: # while迴圈
    print(msg) # 列印使用者操作選單
    index_user_choice = input("請選擇以上功能>>>") # 讓使用者輸入功能
    if index_user_choice == "1": # 如果客戶選擇1查詢
        with open("info.txt", "r", encoding="utf-8") as f: # 開啟相關文字
            user_salary = f.readlines() # 一行一行讀出
        username = input("請輸入要查詢的員工姓名(例如:alex):") # 要求使用者輸入要查詢的員工姓名
        for user_line in user_salary: # 遍歷user_salary
            (user,salary) = user_line.strip("").split() # 將user_salary切割
            if username.lower() == user.lower():  # 判斷使用者輸入的username等於user
                print("%s的工資是:%s" % (user,salary)) # 列印查詢結果
                pass
    elif index_user_choice == "2": # 如果使用者選擇2 修改
        old_user = input("輸入員工姓名(例如:Alex):").strip() # 老員工姓名
        for i in file: # 遍歷file列表
            file = i.strip().split() # 去空格後,再切割為列表
            if old_user in file: # 如果老使用者名稱在file列表中
                old_salary = file[1] # 老工資等於工資
                new_user,new_salary = input("請輸入更改後的員工姓名和工資,用空格分割(例如:Alex 10)").strip().split() # 讓使用者輸入新的工資表,切割為列表
                with open("info.txt", "r", encoding="utf-8") as f:
                    lines = f.readlines() # 逐行讀取f檔案
                with open("info.txt", "w", encoding="utf-8") as f_a: #開啟寫入檔案
                    for line in lines: # 遍歷lines
                        if old_user in lines: #如果老的使用者名稱在lines中
                            line = line.replace(old_user,new_user)
                            # 將老使用者名稱和新使用者名稱交換
                        f_a.write(line) # 將新的使用者名稱寫入到f_a中
                    f_a.close() # 關閉
                with open("info.txt","r",encoding="utf-8") as f:
                    lines = f.readlines()
                with open("info.txt","w",encoding="utf-8") as f_b:
                    for line in lines:
                        if new_user in line:
                            line = line.replace(old_salary, new_salary)
                        f_b.write(line)
                    f_b.close()
                    print("修改成功")
    elif index_user_choice == "3":
        with open("info.txt","r+",encoding="utf-8") as f:
            user_salary = f.readlines()
            new_user_new_salary = input("請輸入要增加員工的姓名和工資,並用空格分割(例如:Eric 100000)")
            f.write(new_user_new_salary + "\n")
            f.close()
    elif index_user_choice == "4":
        sys.exit("再見")
    else:
        print("輸入操作無效")
員工工資表作業

11.函式的相關知識題

# 1.寫函式,檢查獲取傳入列表和元祖物件的所有奇數位索引對應的元素
def func(l):
    return len(l)[:2]
print(func([1,2,3,4]))
# 2.寫函式,判斷使用者傳入的物件(字串、列表、元祖)長度是否大於5
def func(x):
    return len(x) > 5
print(func(2))
# 3.寫函式,檢查傳入列表的長度,如果大於2,那麼僅保留前兩個長度的內容.並將新內容返回給呼叫者
def func(l):
    return l[:2]
print(func([1,2,3,4,5,6])
#4.寫函式,計算傳入字串中【數字】、【字母】、【空格】以及【其他】的個數,並返回結束
def func(dic):
    dic = {"num":0,"alpha":0,"space":0,"other":0}
    for i in dic:
        if i.isdigit():
            dic["num"] += 1
        elif i.isalpha():
            dic["alpha"] += 1
        elif i.isspace():
            dic["space"] += 1
        else:
            dic["other"] += 1
    return dic
print(func("dsa231dhs@@$aio  dsa"))
# 5.寫函式,檢查使用者傳入的物件(字串、列表、元祖)的每一個元素是否含有空內容,並返回結果
def func(x):
    if type(x) is str() and x:
        for i in x:
            if i == " "
                return True
    elif x and type(x) is list or type(x) is tuple
        for i in x:
            if not i:
                return True
    elif not x:
        return True
print(func(" ",[]))
# 6.寫函式,檢查傳入字典的每一個value的長度,如果大於2,那麼僅保留前兩個長度的內容.並將新內容返回給呼叫者
# dic = {"k1":"v1v1","k2":[11,22,33,44]}
# ps:字典中的value只能是字串或列表
def func(dic):
    for k in dic:
       if len(dic[k]) > 2:
            dic[k] = dic[k][:2]
        return dic
dic = {"k1":"v1v1","k2":[11,22,33,44]}
print(func(dic))
# 7.寫函式,接收兩個數字引數,返回比較大的那個數字
def func(a,b):
    return a if a>b else b
print(func(1,5))
# 8.寫函式,使用者傳入修改的檔名,與要修改的內容,執行函式,完成整個檔案的批量修改操作(進階)
def func(filename,old,new):
    with open(filename,encoding="utf-8") as f,open("%s.bak" % filename,"w",encoding = "utf-8") as f1:
       for line in f:
            if old in line:
               line = line.replace(old,new)
            f1.write(line)
    import os
    os.remove(filename)
    os.rename("%s.bak" % filename,filename)
func("NBA","詹姆斯","科比")
函式的相關知識題

 12.函式進階的相關知識題

#1. 寫函式、接收n個數字,求這些引數數字的和。
def sum_func(*args): #1.定義一個可接收多個位置引數的函式,3.接收引數
    total = 0  # 4.定義一個求和的初始值 
    for i in args: # 5.遍歷引數args
        total += i  # 6.將遍歷的所有值相加
    return total # 7.返回求和後的值
print(sum_func(1,2,3,4,5,6)) #2.執行sum_func並傳參 #8.列印結果
#  2.讀程式碼,回答:程式碼中,列印出來的值a,b,c分別是什麼?為什麼?
a = 10  #1. a = 10
b = 20  #2. b = 20
def test5(a,b): #3.定義函式 5.接收a = 20 b = 10
   print(a,b)   #6. 列印20,10
c = test5(b,a) #4. 傳遞b = 20 a = 10 #7. c = None (沒有返回值)
print(c) #8. 列印None
# 結果:a = 20 b = 10 c = None
# 3. 讀程式碼,回答:程式碼中,列印出來的值a,b,c分別是什麼?為什麼?
a = 10  #1. a = 10
b = 20  #2. b = 20
def test5(a,b): #3.定義函式 #5.接收a = 20 b = 10
  a = 3   #6. a = 3
  b = 5   #7. b = 5
  print(a,b) # 8. 列印 3,5
c = test5(b,a) #4. test5(20,10) # 9.c沒有返回值 = None
print(c)  # 10 列印 None
# 結果:a = 3 b = 5 c = None
4.下列程式碼的執行順序
def func(): # 1. 定義函式func
    time.sleep(0.01) #11. 執行秒數
    print("老闆好同事好大家好") #12. 列印
def timmer(f):# 2. 定義函式timer #4.接收func的記憶體地址
    def inner(): #5. 定義函式inner()
        start = time.time() # 9. 定義開始時間
        f() #10. 執行func()
        end = time.time() # 13. 定義結束時間
        print(end - start) # 14. 列印開始到結束的時間
    return inner  #6. timmer到返回inner
func = timmer(func)#3.傳遞func #7. func賦值給timmer()
func() #8 執行timmer() #15. 列印結果
函式進階相關知識題

 13.修飾器相關知識題

#1.編寫裝飾器,為多個函式加上認證的功能(使用者的賬戶密碼來源於檔案)
#要求登入成功一次,後續的函式都無需再輸入使用者名稱和密碼
FLAG = False
def login(func):
    def inner(*args,**kwargs):
        global FLAG
        if FLAG:
            ret = func(*args, **kwargs)
            return ret
        else:
            with open("login",encoding="utf-8") as f:
                for line in f:
                    username = input("使用者名稱:")
                    password = input("密碼:")
                    if username in line and password in line:
                        FLAG = True
                        ret = func(*args, **kwargs)
                        return ret
                    else:
                        print("登入失敗")
    return inner
@login
def shoplist_add():
    print("增加一個商品")
@login
def shoplist_del():
    print("刪除一個商品")

shoplist_add()
shoplist_del()
shoplist_del()
shoplist_del()
shoplist_del()
shoplist_del()
#2.編寫裝飾器,為多個函式加上記錄呼叫功能,要求每次呼叫函式都將被呼叫的函式名稱寫檔案
def log(func):
    def inner(*args,**kwargs):
        with open("log","a",encoding="utf-8") as f:
            f.write(func.__name__+"\n")
        ret = func(*args,**kwargs)
        return ret
    return inner
@log
def shoplist_add():
    print("新增一個物品")
@log
def shoplist_del():
    print("刪除一個物品")
shoplist_add()
shoplist_del()
shoplist_add()
shoplist_del()
shoplist_del()
shoplist_del()
shoplist_del()
#進階作業(選做):
#1.編寫下載網頁內容的函式,要求功能是:使用者傳入一個url,函式返回下載頁面的結果
from urllib.request import urlopen
def get(url):
    code = urlopen(url).read()
    return code
ret = get("http://www.sina.com")
print(ret)

#2.為題目1編寫裝飾器,實現快取網頁內容的功能
#具體:實現下載的頁面存在於檔案中,如果檔案內有值(檔案大小為0),就優先從檔案中讀取網頁內容,否則,就去下載,然後
import os
from urllib.request import urlopen
def cache(func):
    def inner(*args,**kwargs):
        with open("web_cache","rb") as f:
            if os.path.getsize("web_cache"):
                return f.read()
        ret =func(*args,**kwargs)
        with open("web_cache","wb") as f:
            f.write(b"***"+ret)
        return ret
    return inner
@cache
def get(url):
    code = urlopen(url).read()
    return code
ret = get("http://www.baidu.com")
print(ret)
ret = get("http://www.baidu.com")
print(ret)
ret = get("http://www.baidu.com")
print(ret)
修飾器相關知識題

 14.員工資訊查詢

#實現員工資訊表
#檔案儲存格式如下:
#id,name,age,phone,job
#1,Alex,22,13651054608,IT
#2,Egon,23,13304320533,Teacher
#3,Nazha,25,1333235322,IT
#現在需要對這個員工資訊檔案進行增刪改查
#不允許一次性將檔案中的行都讀入記憶體
#可以進行查詢,支援三種語法:
#select 列名1,列名2,...where列名條件
#支援:大於小於等於,還要支援模糊查詢
#示例:
# select name,age where age>22
# select * where job=IT
# select * where phone like 133

dic = {"id":0,"name":1,"age":2,"phone":3,"job":4}
'''整理檔案——將檔案中的內容整理到記憶體裡'''
def get_line(filename):
    with open(filename,encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            line_lis = line.split(",")    
            yield line_lis
def condition_filter():
    '''條件篩選'''
    condition = condition.strip()
    if ">" in condition:
        col,val = condition.split(">")
        g = get_line("user")
        for line_lis in g:
            if int(line_lis[dic[col]]) > int(val):
                yield line_lis
    elif "<" in condition:
        col,val = condition.split("<")
        g = get_line("user")
        for line_lis in g:
            if int(line_lis[dic[col]]) < int(val):
                yield line_lis
    elif "like" in condition:
        col,val = condition.split("like")
        col = col.strip()
        g = get_line("user")
        for line_lis in g:
            if val.strip() in line_lis[dic[col]]:
                yield line_lis
    else:
        col,val = condition.split("=")
        g = get_line("user")
        for line_lis in g:
            if val.upper() in line_lis[dic[col]].upper():
                yield line_lis
def views(view_list,staff_g):
    """展示符合條件的員工資訊"""
    if "*" in view_list:
        view_list = dic.keys()
    for staff_info in staff_g:
        for i in view_list:
            print(staff_info[dic[i]],end=" ")
        print("")
#分析使用者輸入資訊
ret = input(">>>")
view,condition = ret.split("where")
view = view.replace("select","").strip()
view_list = view.split(",")
g = condition_filter(condition)
views(view_list,g)
員工資訊查詢表

 15.生成器與迭代器例項

# 各種推導式的例項
#例1將下列key和值對調
mcase = {"a":10,"b":34}
mcase_frequency = {mcase[k]:k for k in mcase}
print(mcase_frequency)
#例2,合併大小寫對應的value值,將k統一成小寫
mcase = {"a":10,"b":34,"A":7,"Z":3}
mcase_frequency = {k.lower():mcase.get(k.lower(),0)+mcase.get(k.upper(),0) for k in mcase}
print(mcase_frequency)
#例3:過濾掉長度小於3的字串列表,並將剩下的轉換成大寫字母
list1 = ["jame","kb","jodan","wode","li"]
l = [name.upper() for name in list1 if len(name) > 3]
print(l)
#例4:求(x,y)其中x是0-5之間的偶數,y是0-5之間的奇數
ret =[(x,y) for x in range(5) if x %2 ==0 for y in range(5) if y %2 == 1]
print(ret)
#例5:求M中3,6,9組成的列表M=[[1,2,3],[4,5,6],[7,8,9]]
M=[[1,2,3],[4,5,6],[7,8,9]]
ret = [row[2] for row in M]
print(ret)
# 生成器表示式面試題
# 面試題1 執行結果是什麼
def demo():
    for i in range(4):
        yield i
g=demo()
g1 = (i for i in g)
g2 = (i for i in g)
print(list(g1))
print(list(g2))
# [0,1,2,3]
# []

#面試題2 執行結果是什麼
def add(n,i):
    return n+i
def test():
    for i in range(4):
        yield i
g=test() #3
for n in [1,10]:
    g=(add(n,i) for i in g)
print(list(g))
#[20,21,22,23]

# 處理檔案,使用者指定要查詢的檔案和內容,將檔案包含要查詢的內容每一行都輸出到螢幕
def check_file(filename,*args):
    with open(filename,encoding = "utf-8") as f:
        for line in f:
            if "迭代器" in line:
                yield line
for i in check_file("test.py","生成器")
    print(i.strip())

# 寫生成器,從檔案中讀取內容,在每一次讀取到的內容之前加上"***"之後再返回給使用者
def check_file(filename,*args):
    with open(filename,encoding = "utf-8") as f:
        for line in f:
            yield "***" + line
for i in check_file("test.py")
    print(i.strip())
迭代器與生成器例項

 16.內建函式作業

#1.用map把列表中["Allen","Kobe","James","Anthony"]的所有名字加_nb
name = ["Allen","Kobe","James","Anthony"]
print(list(map(lambda x:x+"_nb",name)))
#2.用filter函式處理數字列表將列表中所有的偶數篩選出來
num = [1,3,5,6,7,8]
print(list(filter(lambda x:x%2 ==0,num)))
#3.如下,每個小字典的name對應股票名字,shares對應多少股,price對應股票的價格
portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}]
#3.1 計算購買每支股票的總價
print(list(map(lambda dic:round(dic["shares"]*dic["price"],4),portfolio)))
#3.2 用filter過濾出,單價大於100的股票有哪些
print(list(filter(lambda dic:dic["price"] > 100,portfolio)))
# 面試題
# 1.
d = lambda p:p*2
t = lambda p:p*3
x = 2
x = d(x) #x=2 *2 = 4
x = t(x) #x=12 x = 4 * 3
x = d(x) #x=24 x = 12 * 2
print(x) #列印24
#2.現有兩元祖(("a"),("b")),(("c"),("d"))
#請使用python中匿名函式生成列表[{"a":"c"},{"b":"d"}}]
#解題思路:
#匿名函式,想到與匿名函式有關的內建函式,5種可以key的內建函式#max min sorted filter map
#首先:zip將兩個元祖拉到一起 ("a","c")("b","d")
#利用map將匿名函式組合一起,轉換到列表中
ret = zip((("a"),("b")),(("c"),("d"))) 
print(list(map(lambda tup:{tup[0]:tup[1]},ret)))
#列印結果:[{"a":"c"},{"b":"d"}}]
# 3.以下程式碼的輸出是什麼?請給出答案並解釋
def multipliers():
    return [lambda x:i*x for i in range(4)]
print([m(2) for m in multipliers()])
#[6,6,6,6]
#執行multipliers()
# range(4)取完結果 i = 3
# m(2)給了x傳參 x=2,返回x*i 
# 執行lambda = [2*3,2*3,2*3,2*3]
# 列印[6,6,6,6]
# 同上題
def multipliers():
    return (lambda x:i*x for i in range(4))
print([m(2) for m in multipliers()])
#執行的時候 multipliers是生成器並沒有執行
# m(2) 傳參的給lambda x=2
#執行range(4) return = [2*0,2*1,2*2,2*3]
#列印結果[0,2,4,6]
內建函式和匿名函式

17.遞迴的作業

#1.用遞迴函式求階乘
def func(x):
    if x == 1:
        return 1
    else:
        return x * func(x - 1)
ret = func(6)
print(ret)
#2.用遞迴函式求斐波那契陣列
def feb(x):
    if x == 1 or x == 2:
        return 1
    else:
        return feb(x-1)+feb(x-2)
ret = feb(11)
print(ret) # 遞迴寫斐波那契比較佔記憶體因此不要超過50
# 數太大的容易將python直譯器卡掉
# 2.1.利用字典遞迴斐波那契額
import sys
sys.setrecursionlimit(10000)
def feb1(x,feb={1:1,2:1}) 
    if x in feb:
        return feb[x]
    res = feb1(x-1) + feb1(x-2)
    feb[x] = res
    return res
ret = feb1(9998)
print(ret) # 因為遞迴函式最大限預設為997/998
# 因此利用上面方法我將遞迴函式最大限設定為10000
# 依然非常快推薦使用字典遞迴方式
# 2.2 斐波那契常規方法:
def feb2(x):
    f1 = 1
    f2 = 1
    if x == 1 or x == 2:
        return 1
    else:
        for i in range(3:n+1)
            f1,f2 = f2,f1+f2
            return f2
ret = feb2(99999)  
# 斐波那契常規執行速度最快,切佔記憶體最小不會卡死
#3.遞迴實現漢諾塔
def hanoi(x,a,b,c):
"""x == 1和x == 2可不用,主要用於漢諾塔的移動規則"""
    if x == 1:
        print(a, '-->' ,c)
        return
    if x == 2:
        print(a, '-->' ,b)
        print(a, '-->' ,c)
        print(b, '-->' ,c)
        return
    hanoi(x-1, a, c, b)
    print(a,'-->',c)
    hanoi(x-1, b, a, c)
hanoi(5,"A","B","C")
遞迴作業

 18.正規表示式

import re
# 表示式
def dealwith(express):
    #將表示式的符號處理了 +-替換成-,--替換成+
    express = express.replace("+-","-")
    express = express.replace("--","+")
    return express

def cal_exp_son(exp_son):   # 計運算元表示式
# 只用來計算兩個數之間的乘除法
    if "/" in exp_son:
        a,b = exp_son.split("/")
        return str(float(a)/float(b))
    elif "*" in exp_son:
        a,b = exp_son.split("*")
        return str(float(a)*float(b))
def cal_express_no_bracket(exp):
    # 計算沒有括號的表示式
    # exp是沒有經過處理的最內層的帶括號的表示式
    exp = exp.strip("()")
    # 先乘除後加減
    # 找第一個出現的乘法或除法
    # -40/5*8+2
    # 1-2*-1388335.8476190479
    while True:
        ret = re.search('\d+\.?\d*[*/]-?\d+\.?\d*',exp)
        if ret: # 說明表示式中還有乘除法
            exp_son = ret.group() #子表示式 最簡單的 乘除法 2*5
            ret = cal_exp_son(exp_son) # 10
            exp = exp.replace(exp_son,ret)
            exp = dealwith(exp)
        else:
            ret = re.findall('-?\d+\.?\d*',exp)
            sum = 0
            for i in ret:
                sum += float(i)
            return str(sum)
# 提取括號裡面沒有其他括號的表示式
#3*5+2*3 findall 3*5*6+2*3 = 3*5 2*3 匹不到3*5*6
def remove_bracket(new_express):
    while True:
        ret = re.search('\([^()]+\)',new_express)
        if ret:
            express_no_bracket = ret.group() # 表示式,沒括號
            print("匹配到內部不在有括號的值:",express_no_bracket)
            ret = cal_express_no_bracket(express_no_bracket)
            print(new_express,express_no_bracket,ret)
            new_express = new_express.replace(express_no_bracket,ret)
            new_express = dealwith(new_express)
            print(new_express)
        else:
            print("表示式中已經沒有括號了:",new_express)
            ret = cal_express_no_bracket(new_express)
            return ret
express = '1 - 2 * ( ( 6 0 -3 0  +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
# 去空格
new_express = express.replace(" ","")
print(new_express)
res = remove_bracket(new_express)
print(res)
計算器作業
import re
def math(dic):
    x,y = float(dic["x"]),float(dic["y"])
    if dic["mark"] == "+":return x+y
    elif dic["mark"] == "-":return x-y
    elif dic["mark"] == "*":return x*y
    else:return x/y
def suansu(re_str):
    ret4 = re.search(r'(?P<x>\d+\.?\d*)(?P<mark>[*/])(?P<y>[\-]?\d+\.?\d*)',re_str)
    try:
        while ret4.group():
            re_str = re_str.replace(ret4.group(),str(math(ret4.groupdict())))
            if "--" in re_str:re_str = re_str.replace("--","+")
            if "++" in re_str:re_str = re_str.replace("++","+")
            ret4 = re.search(r'(?P<x>[\-]?\d+\.?\d*)(?P<mark>[*/])(?P<y>[\-]?\d+\.?\d*)',re_str)
    except AttributeError:pass
    ret4 = re.search(r'(?P<x>[\-]?\d+\.?\d*)(?P<mark>[+\-])(?P<y>[\-]?\d+\.?\d*)',re_str)
    try:
        while ret4.group():
            re_str = re_str.replace(ret4.group(),str(math(ret4.groupdict())))
            ret4 = re.search(r'(?P<x>[\-]?\d+\.?\d*)(?P<mark>[+\-])(?P<y>[\-]?\d+\.?\d*)',re_str)
    except AttributeError:return re_str
def main(user_inp):
    while True:
        if not re.search('\([+*/\d.\-]*\)',user_inp):
            print(user_inp)
            return suansu(user_inp)
        else:
            for i in re.findall('\([+*/\d.\-]*\)',user_inp):
                user_inp = user_inp.replace(i,suansu(i.replace('(',"").replace(")","")))
while True:
    print(main('0+'+input(">>>").replace(" ","")))
計算器精簡版
import re
def calculator(e,n=0,round_num=5):
    '''
    實現計算功能
    :param e:算數表示式
    :param n:分成四步處理:n=0:取最內層括號,n=1:計算乘除法
                        n=2:將多個"+--","---"等多個連續的加減號轉換成單個的"+"或"-"
                        n=3:計算加減法
    :param round_num:最後結果保留的小數點位數,預設為5位
    :return:返回計算結果,如果格式錯誤,返回None
    '''
    if " " in e:e = e.replace(" ","")
    if n==0 and re.search('\d\(|\)\d',e):return # 輸入校驗
    regex_lst = ['\(([\d\-\+\.\*\/])+\)','(\d+\.\d+|\d+)(\*|\/)(\-?\d+\.\d+|\d+)','(\+|\-){2,}','(\-|\+)?((\d+\.\d+)|\d+)']
    for step in range(n,len(regex_lst)): # 一個子表示式之後,控制這個子表示式 先計算乘除法 再整理 再計算加減法
        regex = re.compile(regex_lst[step]) #將regex_lst[0]編譯成位元組碼
        while 1:
            tmp = regex.finditer(e) if step==3 else regex.search(e) # tmp是正則匹配的結果,n=1,應該拿到的第一個匹配到乘除法
            if not tmp:
                if step==0:return None if ('(' in e or ')' in e) else round(calculator(e,1),round_num) #step=0去括號
                break
            if step == 3:return sum([float(i.group()) for i in tmp]) #累加 把加減法的最後結果返回
            dic = {0:lambda:calculator(tmp.group()[1:-1],1),1:lambda:float(tmp.group(1))*float(tmp.group(3)) if "*" in tmp.group(2) else float(tmp.group(1))/float(tmp.group(3)),2:lambda:"+" if tmp.group().count("-")%2==0 else "-"}
            e = e.replace(tmp.group(),str(dic[step]()))
def main():
    while 1:
        exp = input(">>>[Q退出]").strip()
        if exp.upper() == "Q":break
        res = calculator(exp)
        if res:print(res)
        else:print("輸入格式錯誤")
main()
計算器大神版

 19.學院管理系統作業

#1.建立北京、上海、2所學校
#2.建立liunx,python,go三個課程,liunx\py 在北京開,go在上海開
#3.課程包含,週期,幾個
#4.班級關聯課程,講師
#5.建立學員時,選擇學校,關聯班級
#6.提供三個角色檢視
    #6.1 學院檢視,登陸,檢視課程,檢視班級
    #6.2 講師檢視,講師可檢視自己教學的班級、課程
                #進階需求:可管理自己的班級,檢視班級學員列表,修改所有管理的學員的成績
    #6.3 管理檢視,建立講師,建立班級,建立課程
#7.上面的操作產生的資料都通過pickle序列化儲存到檔案中
作業需求
# 檔案目錄資訊
'''
+ | homework
    +| bin
        +| start.py
    +| conf
        +| settings.py
    +| core
        +| LOG.py
        +| Main.py
        +| Manager.py
        +| Mypickle.py
        +| School.py
        +| Student.py
        +| Teacher.py
    +| db
        +| studentinfo
        +| classes.ini
        +| course_obj.ini
        +| schoolinfo.ini
        +| teacher_obj.ini
        +| userinfo.ini
    +| log.
        +| LOG.log
檔案目錄
from os import getcwd,path
from sys import path as sys_path
from core import Main
sys_path.append(path.dirname(path.dirname(__file__)))
if __name__ == '__main__':
    Main.main()
bin\start.py
userinfo = r"E:\fullstack\week4\homework4(1)\db\userinfo"
schoolinfo = r"E:\fullstack\week4\homework4(1)\db\schoolinfo"
teacher_obj = r"E:\fullstack\week4\homework4(1)\db\teacher_obj"
student_obj = r"E:\fullstack\week4\homework4(1)\db\student_obj"
classes_obj = r"E:\fullstack\week4\homework4(1)\db\classes_obj"
course_obj = r"E:\fullstack\week4\homework4(1)\db\course_obj"
conf\settings.py
from sys import modules
import hashlib
from conf.settings import *
from core.Manager import Manager
from core.Student import Student
from core.Teacher import Teacher
print(modules["__main__"])
status_dic = {
    "username":None,
    "status":False,
    "role":None
}
def login():
    uer = input("\033[1;34m請輸入您的使用者名稱:\033[0m").strip()
    pwd = input("\033[1;34m請輸入您的密碼:\033[0m").strip()
    md5 = hashlib.md5()
    md5.update( bytes( pwd, encoding="utf-8" ) )
    pwd_md5 = md5.hexdigest()
    with open(userinfo,encoding="utf-8") as f:
        for line in f:
            user,password,role = line.strip().split("|")
            if user == uer and pwd_md5 == password and role == "Manager":
                print( '\033[1;32m歡迎%s使用者登入,您的身份是%s\033[0m'.center( 50, '*' ) % (uer,role) )
                return {'username': user, "role": role}
            elif user == uer and pwd_md5 == password and role == "Teacher":
                print( '\033[1;32m歡迎%s使用者登入,您的身份是%s\033[0m'.center( 50, '*' ) % (uer,role) )
                return {"username": user, "role": role}
            elif user == uer and pwd_md5 == password and role == "Student":
                print( '\033[1;32m歡迎%s使用者登入,您的身份是%s\033[0m'.center( 50, '*' ) % (user,role) )
                return {"username": user, "role": role}

def main():
    print("\033[1;36m 歡迎您登入選課系統\033[0m")
    ret = login()
    if ret:
        role_class = getattr(modules[__name__],ret["role"]) # 根據userinfo檔案當中的最後一項內容反射對應的角色類
        obj = role_class(ret["username"])
        while True:
            for i,j in enumerate(role_class.menu,1):
                print(i,j[0])
            # try:
            num = int(input("\033[1;34m請輸入操作序號:\033[0m"))
            getattr(obj,role_class.menu[num-1][1])()
            # except:
            #     print("\033[1;31m對不起,您輸入的內容有誤!\033[0m")

# if __name__ == "__main__":
#     main()
core\Main.py
from os import path
import sys
import hashlib
from conf.settings import *
from core.Mypickle import MyPickle
from core.Teacher import Teacher
from core.Student import Student
from core.School import *
from core import LOG
class Manager:
    menu = [('建立學校', 'create_school'),
            ('建立學生賬號', 'create_student'),
            ('建立講師賬號', 'create_teacher'),
            ('建立課程', 'create_course'),
            ('建立班級', 'create_class'),
            ('檢視學校', 'show_school'),
            ('檢視學生', 'show_student'),
            ('檢視講師', 'show_teacher'),
            ('檢視課程', 'show_course'),
            ('檢視班級', 'show_class'),
            ('為班級指定老師', 'boundClassTeacher'),
            ('退出', 'exit')]
    def __init__(self, name):
        self.name = name
        self.teacher_pickle_obj = MyPickle( teacher_obj )
        self.course_pickle_obj = MyPickle( course_obj )
        self.student_pickle_obj = MyPickle( student_obj )
        self.class_pickle_obj = MyPickle( classes_obj )
        self.school_pickle_obj = MyPickle( schoolinfo )
        self.obj = LOG.Log()
    @staticmethod
    def userinfo_handle(content):
        with open( userinfo, "a" ) as f:
            f.write( "\n%s" % content )

    def create_school(self):
        school_name = input( "\033[1;34m請輸入要建立的學校名稱:\033[0m" )
        school_course = input( "\033[1;34m請輸入學校的課程\033[0m" )
        school = School( school_name, school_course )
        self.school_pickle_obj.dumpiter( school )
        a = 'Create a school'
        self.obj.record(a)
        print( "\033[1;32m建立成功!!\033[0m" )

    def create_class(self):
        classes_name = input( "\033[1;34m請輸入要班級的名稱:\033[0m" )
        self.show_school()
        school_name = input( "\033[1;34m請輸入學校的名稱:\033[0m" )
        school_g = self.school_pickle_obj.loaditer()
        for schools in school_g:
            if schools.name == school_name:
                self.show_course()
                course = input( "\033[1;34m請輸入學科的名稱:\033[0m" )
                studen_path = path.join( schoolinfo, classes_name )
                open( studen_path, "w" ).close()
                classes_obj = Classes( school_name, classes_name, course, studen_path )
                self.class_pickle_obj.dumpiter( classes_obj )
                b = 'Create a class'
                self.obj.record( b )
                print( "\033[1;32m建立成功!!\033[0m" )
            else:
                print( "\033[1;31m你所輸入的學校不存在,你不能建立\033[0m" )

    def create_course(self):
        course_name = input( "\033[1;34m請輸入課程的名稱\033[0m" )
        course_priod = input( "\033[1;34m請輸入課程的週期\033[0m" )
        course_price = input( "\033[1;34m請輸入課程的價格\033[0m" )
        self.show_school()
        school = input( "\033[1;34m請輸入所屬學校\033[0m" )
        course = Course( course_name, course_priod, course_price, school )
        self.course_pickle_obj.dumpiter( course )
        c = 'Create a course'
        self.obj.record( c )
        print( "\033[1;32m建立成功\033[0m" )

    def create_student(self):
        student_name = input( "\033[1;34m請輸入要建立的學生姓名:\033[0m" )
        student_pwd = input( "\033[1;34m請輸入要建立的學生密碼:\033[0m" )
        self.show_school()
        student_school = input( "\033[1;34m請輸入學生所在學校:\033[0m" )
        self.show_class()
        student_class = input( "\033[1;34m請輸入學生所在的班級:\033[0m" )
        class_g = self.class_pickle_obj.loaditer()
        for clas in class_g:
            if clas.name == student_class:
                md5 = hashlib.md5()
                md5.update( bytes( student_pwd, encoding="utf-8" ) )
                student_pwd_md5 = md5.hexdigest()
                content = "%s|%s|Student" % (student_name, student_pwd_md5)
                Manager.userinfo_handle( content )
                stu_obj = Student( student_name, student_school, clas, )
                MyPickle( clas.student_path ).dumpiter( stu_obj )
                d = 'Create a student'
                self.obj.record( d )
                print( "\033[1;32m建立成功\033[0m" )
                break
            else:
                print( "\033[1;31m您輸入的內容有誤,建立學生失敗\033[0m" )
    def create_teacher(self):
        teacher_name = input( "\033[1;34m請輸入要建立的講師姓名\033[0m" )
        teacher_pwd = input( "\033[1;34m請輸入要建立的講師密碼\033[0m" )
        self.show_school()
        school = input( "\033[1;34m請輸入老師所在學校:\033[0m" )
        md5 = hashlib.md5()
        md5.update( bytes( teacher_pwd, encoding="utf-8" ) )
        teacher_pwd_md5 = md5.hexdigest()
        content = "%s|%s|Teacher" % (teacher_name, teacher_pwd_md5)
        Manager.userinfo_handle( content )
        teacher = Teacher( teacher_name )
        self.teacher_pickle_obj.dumpiter( teacher )
        e = 'Create a teacher'
        self.obj.record( e )
        print( "\033[1;32m建立成功!\033[0m" )
    def show(self, pickle_obj):
        pick_obj = getattr( self, pickle_obj )
        load_g = pick_obj.loaditer()
        for course_obj in load_g:
            for i in course_obj.__dict__:
                print( i, course_obj.__dict__[i] )
            print( "-" * 50 )
    def show_course(self):
        self.show( "course_pickle_obj" )
    def show_school(self):
        self.show( "school_pickle_obj" )
    def show_student(self):
        self.show( "student_pickle_obj" )
    def show_class(self):
        self.show( "class_pickle_obj" )
    def show_teacher(self):
        self.show( "teacher_pickle_obj" )
    def boundClassTeacher(self):
        self.show_class()
        class_name = input( "\033[1;34m請輸入要指定的班級 :\033[0m" )
        self.show_teacher()
        teacher_name = input( "\033[1;34m請輸入要指定的講師 :\033[0m" )
        teach_g = self.teacher_pickle_obj.loaditer()
        for teacher_obj in teach_g:
            if teacher_obj.name == teacher_name:
                teacher_obj.classes.append( class_name )
                self.teacher_pickle_obj.edit( teacher_obj )
                f = 'boundClassTeacher'
                self.obj.record( f )
                print( "\033[1;32m建立成功\033[0m" )
                return
    def exit(self):
        sys.exit()
core\Manager
import pickle
import os
class MyPickle:
    def __init__(self,filename):
        self.filename = filename

    def dumpiter(self,obj):
        with open(self.filename,"ab") as f:
            pickle.dump(obj,f)

    def loaditer(self):
        with open(self.filename,"rb") as f:
            while True:
                try:
                    obj = pickle.load(f)
                    yield obj
                except:
                    break

    def edit(self,obj): # 編輯 修改
        f2 = MyPickle(self.filename+".bak")
        for item in self.loaditer():
            if item.name == obj.name:
                f2.dumpiter(obj)
            else:
                f2.dumpiter(item)
            os.remove(self.filename)
            os.rename(self.filename+".bak",self.filename)
core\Mypickle.py
class Classes:
    def __init__(self,school,name,course,student_path):
        self.school = school
        self.name = name
        self.course = course
        self.student_path = student_path

class Course:
    def __init__(self,name,period,price,school):
        self.name = name
        self.period = period
        self.price = price
        self.school = school
    def __repr__(self):
        return self.name

class School:
    def __init__(self,name,course):
        self.name = name
        self.course = course
core\School.py
import sys
from core import Manager
class Student:
    menu = [('檢視學校', 'show_school'),
            ('檢視班級', 'show_class'),
            ('檢視課程', 'show_course'),
            ('退出', 'quit')]
    def __init__(self,name,student_school,clas):
        self.student_name = name
        self.student_school = student_school
        self.clas = clas
        self.obj = Manager.Manager(name)
    def __repr__(self):  #內建的方法,讓列印的物件豐富起來
        show_str = ''
        for key in self.__dict__:
            if key == 'obj':continue
            show_str +='%s:%s ' % (key,  self.__dict__[key])
        return show_str
    def show_school(self):
        self.obj.show_school()
    def show_class(self):
        self.obj.show_class()
    def show_course(self):
        self.obj.show_course()
    def quit(self):
        sys.exit()
core\Student.py
import sys
from core import Manager
class Teacher:
    menu = [('檢視學校', 'show_school'),
            ('檢視講師', 'show_teacher'),
            ('檢視班級', 'show_class'),
            ('檢視課程', 'show_course'),
            ('退出', 'quit')]
    def __init__(self,name):
        self.obj = Manager.Manager( name )
    def __repr__(self):  #內建的方法,讓列印的物件豐富起來
        show_str = ''
        for key in self.__dict__:
            if key == 'obj':continue
            show_str +='%s:%s ' % (key,  self.__dict__[key])
        return show_str
    def show_school(self):
        self.obj.show_school()
    def show_teacher(self):
        self.obj.show_teacher()
    def show_class(self):
        self.obj.show_class()
    def show_course(self):
        self.obj.show_course()
    def quit(self):
        sys.exit()
core\Teacher.py
import logging
import sys
from log import *

class Log:
    def __init__(self):
        pass

    def record(self,s):
        logger = logging.getLogger()
        fh = logging.FileHandler( "log\LOG.log", encoding="utf-8" )
        formatter = logging.Formatter("%(asctime)s%(levelname)s%[line:%(lineno)d] %(message)s")
        fh.setFormatter(formatter)
        logger.addHandler(fh)
        logging.info(s)
core\LOG.py
# 初始三個角色的賬號
admin|1234|Manager
student|1234|Student
teacher|1234|Teacher
db\userinfo

 

相關文章