• python练习题


    1.随机生成多少位的密码保存在文本内。

    import random,string
    f = open('C:\Users\Administrator\Desktop\new.txt', 'a+')
    # a  追加写,不会请求,打开的文件不存在的话,也会帮你新建一个文件r+  读写模式
    # w+   写读模式
    # a+    追加读模式
    upperStr = string.ascii_uppercase  #string 大写字母
    lowerStr = string.ascii_lowercase    #string 小写字母
    digitStr = string.digits #string 数字
    specialStr = string.punctuation   #string 特殊数字
    allStr = upperStr+lowerStr+digitStr+specialStr #产生密码所需要的字符集
    f.seek(0)#把指针移动到第一位
    all_password = []
    #这个函数是无限循环产生对应的数
    def pw1():
        while True:  #True 表示无限循环
            pw = ''.join(random.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.1234567890!@#$%^&*()+=-><:",random.randint(8, 16)))
        #随机生成8到16位的字符,可以把需要的数字全部填写在里面
            if pw not in all_password:
                not(f.write(pw +'
    '))#写入到文件内
    Num = 1# 输入要产生密码的次数:
    def pws():
        for i in range(Num):
            pwdLen = random.randint(6,11)
        #  print(pwdLen) # 随机生成密码的长度
            pwd1 = random.choice(upperStr) + random.choice(digitStr) + random.choice(lowerStr) + random.choice(specialStr)
            #随机密码必须包含的四个字符:大写字母,小写字母,数字,特殊字符
            pwdRan = random.sample(allStr,pwdLen-4) #除去4个字符外,随机从字符集中取出剩下所需要的字符
            pwd2 = "".join(pwdRan)#  并将该List转化为字符串
            pwd = pwd1+pwd2 # 最终生成的随机密码
            f.write(pwd+'
    ')
            f.flush()
        f.close()
    pws()
    View Code

    2.随机生成双色球

    import random
    def seq():
        qiu = []
        while True:
            hong = random.randint(1,33) #产生一个随机红球
            if hong in qiu:
                continue #跳过本次循环
            qiu.append(hong) #把红色号码添加到列表
            if len(qiu)==6:
                break
        qiu.sort()
        lan = random.randint(1,16) #产生一个随机篮球
        s = ""
        for i in qiu:
            s = s+"%02d " %i #02d表示是2位数的整数,个数自动补0
        print(s+"+ "+"%02d" %lan)
    seq()
    View Code

    3.连续输入几次用户名或密码判断

    import datetime
    def xunhan():
        for i in range(3):
            username = input('请输入你的用户名:').strip()
            password = input('请输入你的密码:').strip()#strip 去除为空的情况
            if username=='xiaoming' and password == '123456':
                print('欢迎%s登陆,今天的日期是%s'%(username,datetime.datetime.today()))
                break
            elif username=='' or password =='':
                print('账号和密码都不能为空!')
            else:
                print('账号/密码错误')
        else:
            print('错误次数过多')
    def xunhuan1():
        count = 0
        while count<3:
            count += 1
            username = input('请输入你的用户名:').strip()
            password = input('请输入你的密码:').strip()
            if username=='tanailing' and password == '123456':
                print('欢迎%s登陆,今天的日期是%s'%(username,datetime.datetime.today()))
                break
            elif username=='' or password =='':
                print('账号和密码都不能为空!')
            else:
                print('账号/密码错误')
        else:
            print('错误次数过多')
    View Code

    4.注册:账号和密码存在文件里面,从文件里面读取数据判断是否已经存在

    f = open('C:\Users\Administrator\Desktop\new.txt','a+')
    f.seek(0)
    res = f.read()
    def zhuce():
        all_user_name = [] #存放所有的用户名
        for r in res.split('
    '):  # ['username,123456', 'username2,abc123']
            #'username,123456' [username, 123456]
            username = r.split(',')[0]
            all_user_name.append(username)
        for i in range(3):
            username = input('username:').strip()
            pwd = input('pwd:').strip()
            cpwd = input('cpwd:').strip()
            if not (len(username)>=6 and len(username)<=20):
            # if len(username)<=6 and len(username)>=20:
                print('用户名长度不合法')
            elif not (len(pwd)>=8 and len(pwd)<=20):
                print('密码长度不合法')
            elif pwd!=cpwd:
                print('两次输入的密码不一致')
            elif username in all_user_name:
                print('用户名已经被注册')
            else:
                user_info = '%s,%s
    '%(username,pwd)
                f.write(user_info)
                print('注册成功!')
                break
        else:
            print('错误次数过多')
        f.close()
    zhuce()
    注册

    5.商品管理(添加,删除,修改,查询)

    """作业:
        1、实现一个商品管理的程序。
            #输出1,添加商品 2、删除商品 3、查看商品
            添加商品:
                商品的名称:xxx  商品如果已经存在的话,提示商品商品已经存在
                商品的价格:xxxx 数量只能为大于0的整数
                商品的数量:xxx,数量只能为大于0的整数
            2、删除商品:
                输入商品名称:
                    iphone 如果输入的商品名称不存在,要提示不存在
            3、查看商品信息:
                 输入商品名称:
                    iphone:
                        价格:xxx
                        数量是:xxx
                    all:
                        print出所有的商品信息 '''
    import json
    def get_file_content():
        with open(FILENAME,encoding='utf-8') as f :
            content = f.read()
            if len(content)>0:
                res = json.loads(content)
            else:
                res = {}
        return res
    def write_file_content(dic):
        with open(FILENAME,'w',encoding='utf-8') as fw:
            json.dump(dic,fw,indent=4,ensure_ascii=False)
    def check_digit(st:str):
        if st.isdigit():
            st = int(st)
            if st > 0:
                return st
            else:
                return 0
        else:
            return 0
    def add_product():
        product_name = input('请输入商品名称:').strip()
        count = input('请输入商品数量:').strip()
        price = input('请输入商品价格:').strip()
        all_products = get_file_content()
        if check_digit(count) == 0:
            print('数量输入不合法')
        elif check_digit(price) == 0:
            print('价格输入不合法')
        elif product_name in all_products:
            print('商品已经存在')
        else:
            all_products[product_name] = {"count":int(count), "price":int(price)}
            write_file_content(all_products)
            print('添加成功!')
    def show_product():
        product_name = input('请输入要查询的商品名称:').strip()
        all_products = get_file_content()
        if product_name=='all':
            print(all_products)
        elif product_name not in all_products:
            print('商品不存在')
        else:
            print(all_products.get(product_name))
    def del_product():
        product_name = input('请输入要删除的商品名称:').strip()
        all_products = get_file_content()
        if product_name in all_products:
            all_products.pop(product_name)
            print('删除成功')
            write_file_content(all_products)
        else:
            print('商品不存在')
    choice = input('请输入你的选择:
     1、添加商品 2、删除商品 3、查看商品信息:')
    if choice == "1":
        add_product()
    elif choice == "2":
        del_product()
    elif choice == "3":
        show_product()
    else:
        print('输入错误,请重新输入!')
    商品添加

     6.把excel内的文字转换为拼音

    例如把“xxxx.xls中的汉字人名转成用户名,写到后面的单元格中,excel在群文件

     例如:中国-王小明 : zg_wangxiaoming

    import xpinyin,xlrd,string
    from xlutils.copy import copy
    book = xlrd.open_workbook(r'xxxxxxxxx.xls')
    sheet = book.sheet_by_index(0)
    p = xpinyin.Pinyin()
    new_book = copy(book)  # 拷贝一分原来的Excel
    new_sheet = new_book.get_sheet(0)  # 获取sheet页
    for i in range(1,sheet.nrows):
        name = sheet.row_values(i)[0]
        name_pinyin = p.get_pinyin(name,'')
        name_pinyin = name_pinyin.replace('wangluo','wl').replace('xianchang','xc').replace('cengke','ck')
        for n in name_pinyin:
            if n not in string.ascii_lowercase:#判断如果不是字母的话,就替换
                res = name_pinyin.replace(n,'_')
                #ck__liuwei
                xhx_count = res.count('_')#取下划线的个数
                if xhx_count>1:#判断下划线如果大于1,就把多个下划线替换成一个下划线
                    res = res.replace('_'*xhx_count,'_')
        new_sheet.write(i,1,res)#
    new_book.save(r'xxxxxxxx')
    转换拼音

     7.删除空文件

    import os
    for cur_dirs,dirs,files in os.walk(r"F:jmter测试数据"):
        print(cur_dirs,dirs,files) #三个值分别代表:文件地址,文件夹,文件
        if len(files)==0 and len(dirs)==0:
           #判断文件和文件夹是否为空
            os.rmdir(cur_dirs)#这里删除不能直接用os.remove,会直接报权限问题
    View Code

     8.循环练习题

    import random
    num = random.randint(1,100)#随机获取之间的数字
    print(num)
    count = 0
    while count<3:#定义循环的次数
        count+=1
        guess = int(input("请输入一个数字:"))
        if guess>num:
            print("大了")
        elif guess == num:
            print("猜对了")
            break #当猜对了这里就直接结束整个循环
            #如果是“continue” 就是结束当前的循环,继续执行下一个循环
        else:
            print("小了")
    
    else:
        print("猜的次数过多,游戏结束")
    猜数字游戏
  • 相关阅读:
    PHP格式化时间戳函数分享
    The Mac App Store isn't working. How to fix?
    sqlite+ef+powertools
    部署node api的二三事
    node 写api几个简单的问题
    基于项目的简单的代码生成器
    h5跳转到app的实现
    几种常用的git命令
    发送post请求几种常见content-type类型
    cors(Cross-origin resource sharing)跨域资源共享
  • 原文地址:https://www.cnblogs.com/test49355--/p/10825501.html
Copyright © 2020-2023  润新知