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)

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 = "
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 = "
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]

    # l3 = li[::2]

    # l4 = li[1:-2:2]

    # l5 = li[-1:]

    # 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(用两种方式)。

    # lis[0][1][2]['k1'][0] = lis[0][1][2]['k1'][0].upper()
    # lis[0][1][2]['k1'][0] = 'TT'

    # lis[0][1][2]['k1'][1] = str(lis[0][1][2]['k1'][1] + 97)
    # lis[0][1][2]['k1'][1] = '100'

    # 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']

s = li[0]+li[1]+li[2]

s = '*'.join(li)

li = s.split("l",1)

li = s.split(' ')

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 = [[','psv',1200],
        [','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":{},
            },
            "望京":{
                "陌陌":{},
                "奔驰":{},
                ":{},
            },
            "三里屯":{
                "优衣库":{},
                "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")
    ":
        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
    ":
        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
# 实现效果:
# 从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("请选择以上功能>>>") # 让用户输入功能
    ": # 如果客户选择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
    ": # 如果用户选择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("修改成功")
    ":
        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()
    ":
        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()
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)
            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

python基础篇实战的更多相关文章

  1. python基础篇---实战---用户登入注册程序

    一.首先了解需求: 1.支持多个用户登入 2.登入成功后显示欢迎,并退出程序 3.登入三次失败后,退出程序,并在下次程序启动尝试登入时,该用户名依然是锁定状态 二.文件代码如下: f = open(& ...

  2. python基础篇-day1

    python基础篇 python是由C语言写的: pass 占位符: del,python中全局的功能,删除内存中的数据: 变量赋值的方法: user,pass = 'freddy','freddy1 ...

  3. python基础篇之进阶

    python基础篇之进阶 参考博客:http://www.cnblogs.com/wupeiqi/articles/5115190.html python种类 1. cpython  使用c解释器生产 ...

  4. python基础篇(六)

    PYTHON基础篇(六) 正则模块re A:正则表达式和re模块案例 B:re模块的内置方法 时间模块time A:时间模块的三种表示方式 B:时间模块的相互转换 随机数模块random A:随机数模 ...

  5. python基础篇(五)

    PYTHON基础篇(五) 算法初识 什么是算法 二分查找算法 ♣一:算法初识 A:什么是算法 根据人们长时间接触以来,发现计算机在计算某些一些简单的数据的时候会表现的比较笨拙,而这些数据的计算会消耗大 ...

  6. python基础篇(一)

    PYTHON基础篇(一) 变量 赋值 输入,输出和导入 A:输入 B:输出 C:导入 运算符 A:算数运算符 B:比较运算符 C:赋值运算符 D:位运算符 E:逻辑运算符 F:成员运算符 G:身份运算 ...

  7. python基础篇(二)

    PYTHON基础篇(二) if:else,缩进 A:if的基础格式和缩进 B:循环判断 C:range()函数和len()函数 D:break,contiue和pass语句 for,while循环 函 ...

  8. python基础篇(三)

    PYTHON基础篇(三) 装饰器 A:初识装饰器 B:装饰器的原则 C:装饰器语法糖 D:装饰带参数函数的装饰器 E:装饰器的固定模式 装饰器的进阶 A:装饰器的wraps方法 B:带参数的装饰器 C ...

  9. python基础篇(四)

    PYTHON基础篇(四) 内置函数 A:基础数据相关(38) B:作用域相关(2) C:迭代器,生成器相关(3) D:反射相关(4) E:面向对象相关(9) F:其他(12) 匿名函数 A:匿名函数基 ...

随机推荐

  1. 说一说MVC的Authentication过滤(四)

    前沿: 一般情况下,在我们做访问权限管理的时候,会把用户的正确登录后的基本信息保存在Session中,以后用户每次请求页面或接口数据的时候,拿到 Session中存储的用户基本信息,查看比较他有没有登 ...

  2. .net core在Ocelot网关中统一配置Swagger

    最近在做微服务的时候,由于我们是采用前后端分离来开发的,提供给前端的直接是Swagger,如果Swagger分布在各个API中,前端查看Swagger的时候非常不便,因此,我们试着将Swagger集中 ...

  3. asp.net core 系列 14 错误处理

    一.概述 本文介绍处理 ASP.NET Core 应用中常见错误的一些方法.主要是关于:开发环境异常页:非开发环境配置自定义异常处理页:配置状态代码页(没有正文响应,http状态400~599的). ...

  4. andrroid 测试那点事

    1.拨号*#*#98284#*#* 2.查看imei号:拔号 *#06# 3.抓取 MTK Log *#*#3646633#*#* 高通平台 *#62564# 4.查看手机的cpu架构信息:adb s ...

  5. Android--拦截系统BroadcastReceiver

    前言 上一篇博客,讲了BroadcastReceiver的一些基础内容,如何注册以及发送一个广播,那是基础,不清楚的可以先看看:Android--BroadcastReceiver.但是在实际开发当中 ...

  6. 在 Vue 结合 Axios 使用过程 中 post 方法,后台无法接受到数据问题

    关于在 vue 中 使用 axios 相关 bug 首先,我们来看下 axios 的 github 传送门 axios 然后我们再介绍下 axios 的作者的 github 传送门 Matt 最后,我 ...

  7. 一纸理解JVM

    JVM,JDK,JRE定义 JVM是Java Virtual Machine(Java虚拟机)的缩写. JDK是Java Development Kit JAVA语言开发工具箱(JAVA核心) JRE ...

  8. 记一次Eureka启动报Failed to start bean 'eurekaAutoServiceRegistration' 。。。错误

    在一次项目迁移的过程中,新导入了两个依赖,结果项目启动就报错,如下: 主要原因是:Failed to start bean 'eurekaAutoServiceRegistration'; neste ...

  9. RabbitMQ消息队列(四)-服务详细配置与日常监控管理

    RabbitMQ服务管理 启动服务:rabbitmq-server -detached[ /usr/local/rabbitmq/sbin/rabbitmq-server -detached ] 查看 ...

  10. mysql数据库备份并且实现远程复制

    一.实现ssh 远程登陆 机器环境: 192.167.33.108 clent 用户:crawler 192.167.33.77 server 用户:crawler 1.客户端 生成密钥 /home/ ...