python学习笔记 day11 作业讲解

使用函数分别实现用户三次登录功能,新用户注册功能,购物功能

def func1():
    '''
    实现三次登录功能
    '''
    count=3
    username,password=func2()
    while count:
        usm=input("登陆用户名>>>")
        psd=input("登陆密码>>>")
        if usm==username and psd==password:
            print("登录成功")
            return True
        else:
            print("您还有{}次机会尝试".format(count-1))
            msg=input("continue(Y or N)?")
            if msg=='N':
                return False
                break

def func2():
    """
    实现新用户注册功能
    """
    username=input("注册用户名>>>")
    password=input("注册的用户名密码>>>")
    return username,password

def func3():
    """
    实现购物功能
    """
    money=input("工资>>>")
    d={'牛奶':100,'香蕉':50,'苹果':30,'橘子':20}
    d2={}
    if func1():
        while 1:
            for key in d:
                print(key,d[key])
            shopping=input("请输入要购买的商品名称或者Q(q)退出>>>")
            number=input("请输入需要购买的数目:")
            if shopping.upper()=='Q':
                print("您购买的商品为{}".format(d2))
                break
            else:
                if shopping in d:
                    if d[shopping]*int(number)<float(money):
                        if shopping in d2:
                            d2[shopping]+=number
                        else:
                            d2[shopping]=number

                else:
                    print("请您重新输入要购买的商品名")

func3()

写函数,计算传入字符串中数字,字幕,空格以及其他字符的个数,并返回结果:

def func(s):
    count_n,count_alpha,count_space,count_other=0,0,0,0
    for i in s:
        if i.isdigit():
            count_n+=1
        elif i.isalpha():
            count_alpha+=1
        elif i.isspace():
            count_space+=1
        else:
            count_other+=1
    return count_n,count_alpha,count_space,count_other
print(func('12sdkj23  skdjk_=!'))

写函数,返回比较大的数字:

主要是为了因为三元运算: 条件为True的结果  if 条件 else 条件为False的结果

def func(a,b):
    return a if a>b else b
print(func(2,6))

运行结果:

 写函数,用户传入要修改的文件名,与要修改的内容

import os
def func(filename,content):
    with open(filename,mode='r+',encoding='utf-8') as file1,open('info2',mode='w',encoding='utf-8') as file2:
        for line in file1:
            if 'xuanxuan'in line:
                line=line.replace('xuanxuan',content)
            file2.write(line)
    os.remove('info')
    os.rename('info2','info')
func('info','璇璇')

talk is cheap,show me the code
原文地址:https://www.cnblogs.com/xuanxuanlove/p/9562053.html