Python练习

1.。while,for循环小习题

#1、使用while循环输入 1 2 3 4 5 6 8 9 10
'''
count = 0
while count < 10:
    count += 1  # count = count + 1
    if count == 7:
        print(' ')
    else:
        print(count)

count = 0
while count < 10:
    count += 1  # count = count + 1
    if count == 7:
        continue
    print(count)
'''
#2、输出 1-100 内的所有奇数
#方法一:
# count = 1
# while count < 101:
#     print(count)
#     count += 2
#方法二:
# count = 1
# while count < 101:
#     if count % 2 == 1:
#         print(count)
#     count += 1

#3、求1-2+3-4+5 ... 99的所有数的和
# sum = 0
# count = 1
# while count < 100:
#     if count % 2 == 0:
#         sum = sum - count
#     else:
#         sum = sum + count
#     count += 1
# print(sum)

#4、用户登陆(三次机会重试)
#input 心中有账号,密码 while

i = 0
while i < 3:
    username = input('请输入账号:')
    password = int(input('请输入密码:'))
    if username == '咸鱼哥' and password == 123:
        print('登录成功')
    else:
        print('登录失败请重新登录')
    i += 1

#5、计算 1 - 2 + 3 ... + 99 中除了88以外所有数的总和
方法1:
i=1
sum=0
while i <100:
    if i==88:
        i += 1
        continue
    if i%2!=0:
        sum=sum+i
    else:
        sum=sum-i
    i += 1
print(sum)
-----------------------------------
方法2:
i=0
j=-1
sum=0
while i<99:
    i=i+1
    if i==88:
        continue
    else:
        j = -j
        sum=sum+i*j

print(sum)

#6、⽤户登陆(三次输错机会)且每次输错误时显示剩余错误次数(提示:使⽤字符串格式化)
方式一:
i = 3
username = "yangxiaoer"
password = "123456"
while i>=0:
    name = input("请输入你的用户名:")
    if name == username:
        passwd = input("请输入你的密码:")
        if passwd == password:
            print("登录成功。请稍后")
            print('''
            username: %s
            password: %s
            '''%(username,password))
            break
        else:
            print("你的密码错误 请重新输入")
            print("你还有%s次机会" % (i-1))
            if i == 0:
                print('您的机会已经用完,结束本次操作')
                break
            continue
    else:
        print("你的用户名错误!请重新输入")
        print("你还有%s次机会"%(i-1))
    i -= 1
----------------------------------------------------
方式2:
username = "yangxiaoer"
password = "123456"
i = 3
while i > 0:
    zh = input("请输入你的账号:")
    i -= 1
    if zh == username:
        mm = input("请输入你的密码:")
        if mm == password:
            print("验证成功.正在登陆......")
            print('''恭喜你登陆成功!
            欢迎用户进入
            用户名 :%s
            密码   :%s
            '''%(zh,mm))
            break
        else:
            if i == 0:
                print("你的机会已经没了!game over 下次见!")
                answer = input('再试试?Y or N')
                if answer == 'Y':
                    i = 3
            print("密码错误,请重新输入")
            print("你还有"+str(i)+"次机会")
    else:
        print("请输入正确的用户名!")
        if i == 0:
            print("你的机会已经没了!")
            answer = input('再试试?Y or N')
            if answer == 'Y':
                i = 3
        print("你还有" + str(i) + "次机会")
else:
    print('你TM要不要脸')
函数篇:
1.写函数,接受N个数字,求这些参数数字的和。
def sun_func(*args):
    total = 0
    for i in args:
        total += i
    return total

print(sun_func(1,2,3,9,34,543))


2.读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么?
a = 10
b = 20

def test(a, b):
    print(a, b)

c = test(b, a)
print(c)

#(20, 10)
#None

3.读代码,回答:代码中,打印出来的值的a,b,c分别是什么?为什么?
a = 10
b = 20

def test2(a, b):
    a = 3
    b = 5
    print(a, b)

c = test2(b, a)
print(c)

#(3, 5)
#None


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

def func(lis):
    return lis[1::2]

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

def func(x):
    return len(x) > 5

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

def func(lis):
    if len(lis) > 2:
        return lis[:2]
但是切片有一个特性,多了不报错,所以可以这样写
def func(lis):
    return lis[:2]

4.写函数,计算传入字符串中【数字】、【字母】、【空格】以及【其他】的个数,并返回结果。

def func(s):      # 'fsadsad432 edfd@#$'
    num = 0       # 计算数字的个数
    alpha = 0     # 字母
    space = 0     # 空格
    other = 0     # 其他

    for i in s:
        if i.isdigit():
            num += 1
        elif i.isalpha():
            alpha += 1
        elif i.isspace():
            space += 1
        else:
            other += 1
    return num,alpha,space,other

print(func('fsadsad432 edfd@#$'))

#结果
#(3, 11, 1, 3)

但是这样有个问题,就是没人知道你传回来的是什么,如果需要知道传回来的是什么,需要看源代码。所以最好要用字典。
def func(s):      # 'fsadsad432 edfd@#$'
    dic = {'num':0,'alpha':0,'space':0,'other':0}

    for i in s:
        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('fsadsad432 edfd@#$'))

#结果
#{'alpha': 11, 'num': 3, 'other': 3, 'space': 1}

5.写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容,并返回结果。
# 'sdsad sad a' 对于字符串来说,元素为空内容表示为空格
# [1,2,3,4,'',[],()] 对于列表和元组来说,空内容表示''或[]或()

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

#这种情况下,不需要最后的else,因为内容中没有空内容的话,默认return None,相当于False

6.写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
# dic = {'k1':'v1v1','k2':[11,22,33,44]}
# PS:字典中的value只能是字符串或列表

def func(dic):
    for k in dic.values():
        pass
#一般不这么写,因为正常情况下,vlaue里面的值很大,有可能是嵌套的列表或者字典,如果直接取values,比较浪费内存。

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

8.写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作。

def func(filename, old, new):
    with open(filename, encoding="utf-8") as f, open("%s.bak" % filename, "w", encoding="utf-8") as f2:
        for line in f:
            if old in line:
                line = line.replace(old, new)
            # 写文件
            f2.write(line)

    import os
    os.remove(filename)  # 删除文件
    os.rename("%s.bak" % filename, filename)  # 重命名文件

2.

装饰器篇

装饰器篇:
1.编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码。

def login(func):
    def inner(*args, **kwargs):
        """登录程序
        """
        username = input('username:')
        password = input('password:')
        if username == 'boss_gold' and password == '22222':
            ret = func(*args, **kwargs)  # func是被装饰的函数
            return ret
        else:
            print('登录失败')

    return inner


@login
def shoplist_add():
    print('增加一件物品')


@login
def shoplist_del():
    print('删除一件物品')

shoplist_add()
shoplist_del()

# 但是这样有一样不好,就是运行了shoplist_add()之后再运行shoplist_del()还是要输入 用户名和密码。

FLAG = False
def login(func):
    def inner(*args, **kwargs):
        global FLAG
        """登录程序
        """
        if FLAG:
            ret = func(*args, **kwargs)  # func是被装饰的函数
            return ret
        else:            
            username = input('username:')
            password = input('password:')
            if username == 'boss_gold' and password == '22222':
                FLAG = True
                ret = func(*args, **kwargs)  # func是被装饰的函数
                return ret
            else:
                print('登录失败')

    return inner


@login
def shoplist_add():
    print('增加一件物品')


@login
def shoplist_del():
    print('删除一件物品')

shoplist_add()
shoplist_del()


# 2.编写装饰器,为多个函数加上记录调用功能,要求每次调用函数都将被调用的函数名称写入文件。

def log(func):
    def inner(*args, **kwargs):
        with open('log', 'a', encoding='utf-8') as f:
            f.write(func.__name__ + '
')
        ret = func(*args, **kwargs)
        return ret

    return inner

@log
def shoplist_add():
    print('增加一件物品')


@log
def shoplist_del():
    print('删除一件物品')

shoplist_add()

生成器篇

3.处理文件,用户指定要查找的文件和内容,将文件中包含要查找内容的每一行都输出到屏幕
def check_file(filename,aim):
    with open(filename,encoding='utf-8') as f:   #句柄 : handler,文件操作符,文件句柄
        for i in f:
            if aim in i:
                yield i

g = check_file('1.复习.py','生成器')
for i in g:
    print(i.strip())

4.写生成器,从文件中读取内容,在每一次读取到的内容之前加上‘***’之后再返回给用户。
def check_file(filename):
    with open(filename,encoding='utf-8') as f:   #句柄 : handler,文件操作符,文件句柄
        for i in f:
            yield '***'+i

for i in check_file('1.复习.py'):
    print(i.strip())
原文地址:https://www.cnblogs.com/dongye95/p/10159510.html