PYTHON基础练习题

1、持续输入数据、输完之后退出

with open('test4.txt','w',encoding='utf-8') as f:
    while True:
        inp = input("请输入内容:")
        if inp == 'q':
            break
        f.write(inp + '
')
with open('test4.txt','r',encoding='utf-8') as f:
    print(f.read())
View Code

2、验证用户名和密码,用户名和密码存在文件中

with open('test3.py',encoding='utf8') as f:
    d = dict()
    for line in f:
        vvv=line.strip('
').split(":")[0]
        kkk=line.strip('
').split(":")[1]
        if not len(line):
            continue
        d[vvv] = kkk
    while True:
        a = input("用户名:").strip()
        b = input("密码:").strip()
        if a in d.keys() and b == d[a]:
            print("登陆成功")
        else:
            print("用户名或密码错误")
View Code

3、生成5位的随机验证码

import random
sts = ''
for i in range(5):
    sts += random.choice([str(random.randint(0,9)),chr(random.choice([random.randint(65,90),random.randint(97,122)]))])
print(sts)
#65-90对应小写字母、97-122对应大写字母
View Code

 4、题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

lis = [1,2,3,4]
k=[]
for a in lis:
    for b in lis:
        for c in lis:
            d=str(a)+str(b)+str(c)
            if d[0] != d[1] and d[1] != d[2] and d[0] !=d[2]:
                k.append(int(d))
print(len(k))
print(k)
24
[123, 124, 132, 134, 142, 143, 213, 214, 231, 234, 241, 243, 312, 314, 321, 324, 341, 342, 412, 413, 421, 423, 431, 432]
View Code

 5、使用循环实现修改文件内容

import os
def modify(filename,old,new):
    with open('test.log','r',encoding='utf8') as read_f,#换行书写
         open('bak.swap','w',encoding='utf8') as write_f:
            for line in read_f:
                if old in line:
                    line=line.replace(old,new)
            write_f.write(line)
    os.remove(filename)
    os.rename('bak.swap',filename)
modify('test.log','test','TEST')
View Code

 6、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

def decide(st):
    dig=0      #此处也可以将类型和数量放到字典中,函数最后返回字典
    alp=0
    spa=0
    oth=0
    for i in st:      
        if i.isdecimal():  
            dig=dig+1        #等于dig+=1,要注意和dig=+1的区别(=+并不是简写,a =+ a直接对a的赋值,±符号代表的是正负,即a =+ b其实就是a = b)
        elif i.isalpha():
            alp=alp+1
        elif i.isspace():
            spa=spa+1
        else:
            oth=oth+1
    print("数字个数:%s 字母个数:%s 空格个数:%s 其他个数:%s "%(dig,alp,spa,oth))

decide('asdaadsdasd123123123    !@#$%^&')
View Code

7、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

def decide(st):
    if len(st) > 5:
        print("大于5")
    else:
        print("长度小于等于5")
decide('asdad')
View Code

8、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

def decide(lis):
    if  len(lis) > 2:
        lis=lis[0:2] 
    return lis
print(decide([1,2,3,4,4]))
View Code

9、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

def choice(seq):
    lis = []
    for i in seq:
        if seq.index(i)%2 != 0:
            lis.append(i)
    return lis
a=['a','b','c','d','e','f','g','h']
print(choice(a))

或者采用切片的方式:
def func2(seq):
    return seq[::2]
print(func2([1,2,3,4,5,6,7]))
View Code

10、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。字典中的value只能是字符串或列表

di = {"k1": "v1v1", "k2": [11,22,33,44]}
def take(dic):
    for value,key in dic.items():
        if len(key) >2:
            print(key)
            dic[value]=key[:2]
    return dic
print(take(di))
View Code

 11、编写一个执行的时间是随机的函数

import time,random
def cal():
    st_t = time.time()
    time.sleep(random.randint(0,9))
    ed_t = time.time()
    all = ed_t-st_t
    print("函数执行时间是:%s秒"%all)

cal()
View Code

12、利用装饰器计算函数运行时间

import time,random
def timer(fun):
    def wrapper():
        st_t = time.time()
        fun()
        ed_t = time.time()
        all = ed_t - st_t
        print("函数执行时间是:%s秒" % all)
    return wrapper
@timer  #test=tiemr(test)
def cal():
    time.sleep(random.randint(0,9))
cal()
View Code

13、编写装饰器,为函数加上认证的功能

import time,random
def timer(fun):
    def wrapper():
        with open('test3.py', encoding='utf8') as f:
            d = dict()
            for line in f:
                vvv = line.strip('
').split(":")[0]
                kkk = line.strip('
').split(":")[1]
                if not len(line):
                    continue
                d[vvv] = kkk
            while True:
                a = input("用户名:").strip()
                b = input("密码:").strip()
                if a in d.keys() and b == d[a]:
                    print("登陆成功")
                    break
                else:
                    print("用户名或密码错误")
        fun()
    return wrapper
@timer
def cal():
    time.sleep(random.randint(0,9))
    print("函数执行成功!")
cal()
View Code

14、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式

def auth(auth_type='file'):#这里的变量所有内部函数都能接收到
    def auth2(func):
        def wrapper(*args,**kwargs):
            if login_status['user'] and login_status['status']:
                return func(*args,**kwargs)
            if auth_type == 'file':
                with open(db,encoding='utf-8') as f:
                    dic=eval(f.read())
                name=input('username: ').strip()
                password=input('password: ').strip()
                if name in dic and password == dic[name]:
                    login_status['user']=name
                    login_status['status']=True
                    res=func(*args,**kwargs)
                    return res
                else:
                    print('username or password error')
            elif auth_type == 'sql':
                pass
            else:
                pass
        return wrapper  #返回给auth2
    return auth2  #返回给@auth

@auth()注意这里是带()的,代表运行
def index():
    print('index')
index()
@auth(auth_type='file') def home(name): print('welcome %s to home' %name)

#找时间再练一下

 15、利用迭代器原理读取文件内容

t=open('haproxy.conf').__iter__()
while 1:
    try:
        print(t.__next__(), end='')
    except StopIteration:
        break
View Code

 16、

# 1、文件内容如下,标题为:姓名,性别,年纪,薪资
# egon male 18 3000
# alex male 38 30000
# wupeiqi female 28 20000
# yuanhao female 28 10000
#
# 要求:
# 从文件中取出每一条记录放入列表中,
# 列表的每个元素都是{'name':'egon','sex':'male','age':18,'salary':3000}的形式
with open('test3.py') as f:
    lis=( line.split() for line in f )
    info=[{'name':name,'sex':sex,'age':age,'salary':salary} for name,sex,age,salary in lis]
    print(info)
#根据1得到的列表,取出薪资最高的人的信息
print(max(info,key=lambda dic:dic['salary']))
#根据1得到的列表,取出最年轻的人的信息
print(max(info,key=lambda dic:dic['age']))
# 根据1得到的列表,将每个人的信息中的名字映射成首字母大写的形式
for dic in info:
    dic['name']=dic['name'].title()
print(info)

 17、九九乘法表

for  i in range(1,10):
    for j in range(1,i+1):
        print("%d * %d = %d	"%(i,j,i*j),end='')
    print()

 18、电子书自动翻页,可以选择手动翻页

import time
def read(file,line=1):
    with open(file,'r',encoding='utf8') as f:
        f.seek(0,2)
        end=f.tell()
        f.seek(0,0)
        inp=input("是否开启自动模式(y/n)")
        if inp == 'y':
            while True:
                for  i in range(line):
                    print(f.readline(),end='')
                time.sleep(1)
                cur=f.tell()
                if cur == end:
                    print("牛逼啊看完了")
                    break
        else:
            choice='n'
            f.seek(0, 2)
            end = f.tell()
            f.seek(0, 0)
            while True:
                for i in range(line):
                    print(f.readline(),end='')
                # else:
                #     print("输入n翻页")
                if f.tell() == end:
                    print("牛逼啊看完了")
                    break
                choice=input(">>>")
read('1.txt')
View Code

 19、用户登录验证简单版:

dic = {'aaa':123,'sss':123,'bbb':123}
count=0
while True:
    name=input('请输入用户名:')
    mima=input('请输入密码:')
    try:
        mima=int(mima)
    except:
        print("请输入数字密码")
        exit(1)
    if name in dic.keys() and mima == dic[name]:
        print('恭喜%s登陆成功!'%name)
    else:
        print('用户名或密码错误')
        count += 1
    if count == 3:
        print('验证错误超过3次,程序退出')
        break
View Code

 20、斐波那契数列

a=1
b=1
for fn in range(2,100):
    if fn == b + a:
        print(fn)
        a,b=b,fn


原文地址:https://www.cnblogs.com/sxdpython/p/12670740.html