python基础练习题

时间:2023-02-24 07:54:23

 

1.验证三次用户登录

#!/usr/bin/python env
# coding:utf-8
# 验证三次用户登录
count = 0
while count < 3:
username = input("输入账号:")
pwd = input("输入密码:")
if username == "zq" and pwd == "zq":
print("登录成功")
break
else:
print("账号或者密码错误")
count += 1
print("退出系统!!!!")

 2.随机生成四位数

# 随机生成4位数
import random


def ident_code(num=4):
res = ""
for i in range(num):
# 数字0-9
num1 = str(random.randint(0, 9))
# 大写字母A-Z
# a = chr(random.randint(65, 90))
# 小写字母a-z
b = chr(random.randint(97, 122))
res += random.choice([num1, b])
return res


print(ident_code())


3.99乘法表

# 99乘法表
for i in range(1, 10):
    string = ""
    for j in range(1, i + 1):
        string += str(j) + " * " + str(i) + " = " + str(i * j) + "\t"
    print(string)

 4.文件操作

# 文件操作去取文件中空行 并将zhang改为zzzzzzzzzz
with open('data_txt.py', encoding="utf-8") as f:
    with open('temp.py', 'w', encoding="utf-8") as f1:
        # 要改数据的行号
        res_line = []
        # 保存除去空行后的数据
        del_n_data = []
        data = f.readlines()
        for i in data:
            if len(i) > 1:
                del_n_data.append(i)
        for k,v in enumerate(del_n_data):
            if v.startswith("zhang") and len(v) == 6:
                res_line.append(k)
        for i in res_line:
            del_n_data[i] = "zzzzzzzzzzzzzzz\n"
        print(del_n_data)
        f1.writelines(del_n_data)

 

5.读取文件的最后一行

# 读取文件最后一行 循环文件的推荐方式
with open('20190225.log', 'rb') as f:
    for i in f:
        offs = -10
        while True:
            f.seek(offs, 2)
            data = f.readlines()
            #最后一行数据+上面数据 用列表索引-1,可取到最后一行数据
            if len(data) > 1:
                print(data[-1].decode("utf-8"))
                break
            #data长度小于1,表示未读到大于一行的数据 添加offs偏移量
            offs *= 2

6.斐波那契数列

# 斐波那契数列
class Fib:
    def __init__(self, num):
        self._x = 1
        self._y = 1
        self.num = num

    def __iter__(self):
        return self

    def __next__(self):
        self._x, self._y = self._y, self._x + self._y
        if self._x > self.num:
            raise StopIteration("结束")
        return self._x

    def show_fib(self):
        l = []
        for i in self:
            l.append(i)
        return l

#求1000内的数
f1 = Fib(10000)
print(f1.show_fib())
 

 7.生成器 统计每个省份的年龄

# 生成器 统计每个省份的年龄
''' b.txt
{'name': '北京', 'age': 20}
{'name': '上海', 'age': 33}
{'name': '广州', 'age': 28}
{'name': '深圳', 'age': 40}
'''
def get_age():
    with open('b.txt',encoding='utf-8') as f:
        for i in f:
            yield i
g = get_age()
all_age = sum(int(eval(i)['age']) for i in g)

g = get_age()
def show_age():
    for i in g:
        print('省份:%s 人口平均年龄:%.2f%%' %(eval(i)['name'],100*eval(i)['age']/all_age))

show_age()

 8.装饰器验证用户账号登录

# 简单账号密码验证
# 账号 密码
user_list = [
    {'username': 'zxq', 'passwd': 'zxq'},
    {'username': 'zq', 'passwd': 'zq'},
]

# 用户状态
current_status = {'username': None, 'login': False}

def check_passwd(func):
    def wrapper(*args, **kwargs):
        if current_status['username'] and current_status['login']:
            res = func(*args, **kwargs)
            return current_status['username']
        username = input('username:'.strip())
        passwd = input('password:'.strip())
        for user_dict in user_list:
            if username == user_dict['username'] and passwd == user_dict['passwd']:
                current_status['username'] = username
                current_status['login'] = True
                res = func(*args, **kwargs)
                return current_status['username']
        else:
            print('用户名或者密码错误')

    return wrapper


def index():
    print('hi, guest ,welcome to my index')
    return "ok_index"

@check_passwd
def home():
    print('hi, %s ,welcome home' % (current_status['username']))
    return "ok_home"

@check_passwd
def shop():
    print('hi, %s ,welcome shop' % (current_status['username']))
    return 'ok_shop'

index()
home()
shop()

9.函数闭包带参数装饰器 验证用户登录

# 基于文件账号密码验证
user_list = [
    {'username': 'zxq', 'passwd': 'zxq'},
    {'username': 'zq', 'passwd': 'zq'},
]

current_status = {'username': None, 'login': False}


def auth(auth_type='filedb'):
    def check_passwd(func):
        def wrapper(*args, **kwargs):
            if auth_type == 'strdb':
                print('认证类型是:%s' % (auth_type))
                if current_status['username'] and current_status['login']:
                    res = func(*args, **kwargs)
                    return 'ok'
                username = input('username:'.strip())
                passwd = input('password:'.strip())
                for user_dict in user_list:
                    if username == user_dict['username'] and passwd == user_dict['passwd']:
                        current_status['username'] = username
                        current_status['login'] = True
                        res = func(*args, **kwargs)
                        return 'ok'
                else:
                    print('用户名或者密码错误')
            elif auth_type == 'filedb':
                print('认证类型是:%s' % (auth_type))
            else:
                print('认证类型是:%s' % ('未知'))

        return wrapper

    return check_passwd


@auth(auth_type='strdb')
def index():
    print('hi, guest,welcome')


@auth(auth_type='strdb')
def home():
    print('hi, %s,welcome home' % (current_status['username']))
    return "ok"


@auth(auth_type='strdb')
def shop():
    print('hi, %s,welcome shop' % (current_status['username']))
    return 'ok'


index()
home()
shop()
10.文件增删改查
#!/usr/bin/python env
# coding:utf-8
import os
def file_handler(backend_data,res=None,type='fetch'):
    if type == 'fetch':
        with open('haproxy.conf','r') as read_f:
            tag=False
            ret=[]
            for read_line in read_f:
                if read_line.strip() == backend_data:
                    tag=True
                    continue
                if tag and read_line.startswith('backend'):
                        # tag=False
                        break
                if tag:
                    print('\033[1;45m%s\033[0m' %read_line,end='')
                    ret.append(read_line)
        return ret
    elif type == 'change':
        with open('haproxy.conf', 'r') as read_f, \
                open('haproxy.conf_new', 'w') as write_f:
            tag = False
            has_write = False
            for read_line in read_f:  # server
                if read_line.strip() == backend_data:
                    tag = True
                    continue
                if tag and read_line.startswith('backend'):
                    tag = False
                if not tag:
                    write_f.write(read_line)
                else:
                    if not has_write:
                        for record in res:
                            write_f.write(record)
                        has_write = True
        os.rename('haproxy.conf', 'haproxy.conf.bak')
        os.rename('haproxy.conf_new', 'haproxy.conf')
        os.remove('haproxy.conf.bak')

def fetch(data):
    # print('\033[1;43m这是查询功能\033[0m')
    # print('\033[1;43m用户数据是\033[0m',data)
    backend_data='backend %s' %data
    return file_handler(backend_data)



def add():
    pass

def change(data):
    # print('这是修改功能')
    # print('用户输入的数据是',data)
    backend=data[0]['backend'] #文件当中的一条记录 www.oldboy1.org
    backend_data='backend %s' %backend #backend www.oldboy1.org
    #       server 2.2.2.4 2.2.2.4 weight 20 maxconn 3000

    old_server_record='%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[0]['record']['server'],
                                                              data[0]['record']['server'],
                                                              data[0]['record']['weight'],
                                                              data[0]['record']['maxconn'])

    new_server_record = '%sserver %s %s weight %s maxconn %s\n' % (' ' * 8, data[1]['record']['server'],
                                                                 data[1]['record']['server'],
                                                                 data[1]['record']['weight'],
                                                                 data[1]['record']['maxconn'])
    print('用户想要修改的记录是',old_server_record)
    res=fetch(backend) #fetch('www.oldboy1.org')
    print('来自change函数--》',res)
    if not res or old_server_record not in res:
        return '你要修改的记录不存在'
    else:
        index=res.index(old_server_record)
        res[index]=new_server_record

    res.insert(0,'%s\n' %backend_data)
    file_handler(backend_data,res=res,type='change')


def delete():
    pass

if __name__ == '__main__':
    msg='''
    1:查询
    2:添加
    3:修改
    4:删除
    5:退出
    '''
    msg_dic={
        '1':fetch,
        '2':add,
        '3':change,
        '4':delete,
    }

    while True:
        print(msg)
        choice=input('请输入你的选项:').strip()
        if not choice:continue
        if choice == '5':break

        data=input('请输入你的数据:').strip()

        if choice != '1':
            data=eval(data)

        res=msg_dic[choice](data)
        print('最终结果是--》',res)

 11.购物车

#购物车
product_list = [
    ('Mac',9000),
    ('kindle',800),
    ('tesla',900000),
    ('bike',2000),
]
shopping_car = []
money = raw_input('Please input your money:')
if money.isdigit():
    money=int(money)
    print(u'            商品清单        ')
    check_status = 'True'
    while check_status:
        for k,v in enumerate(product_list,1):
            print(u'商品编号:' + str(k) + u',商品名称:' + v[0] + u',商品价格:' + str(v[1]))
        choice=raw_input(u'选择购买商品编号[退出,请按:q]:'.encode('gbk'))
        
        #判断整数
        if choice.isdigit():
            #输入正确
            choice=int(choice)
            try:
                if choice > 0 and choice <= len(product_list) + 1 :
                    #取出商品
                    p_item=product_list[choice - 1]
                    #判断钱数,商品加入购物车,余额减除
                    if p_item[1] < money:
                        money -= p_item[1]
                        shopping_car.append(p_item)
                    else:
                        print(u'余额不足,还剩%s'%money)
                    print(p_item)
                    #输入不是整数
            except:
                print(u'输入编号错误!!!!!!!!!!!!!!!')
        
        
        #退出
        elif str(choice) == 'q':
            print(u'------------您已经购买如下商品----------------')
            #循环遍历购物车里的商品,购物车存放的是已买商品
            for i in shopping_car:
                print(i)
            print(u'您还剩%s元钱'%money)
            break
        
        #非法输入
        else:
            print('invalid input!!!!!!!!!!!!!!!')
else:
    print('invalid input!!!!!!!!!!!!!!!')