函数之间的互相调用

test1

def a():
    print("AAAAAAAAAAAAAA")

def b():
    a()
    print("BBBBBBBBBBBBBBB")
    a()

# 调用
b()
AAAAAAAAA
BBBBBBBBBB
AAAAAAAAAAA

练习1:加入购物车

判断用户是否登录,如果登录,成功加入购物车,否则提示请登录之后添加。

islogin = False     # 用于判断用户是否登录的变量,默认没有登录
user = 'user1'      # 用户名
pwd = '123'         # 密码

def add_shoppingcart(goodsName):
    global islogin
    if islogin:
        if goodsName:
            print("成功将{}加入购物车".format(goodsName))
        else:
            print("没有选择任何商品")
    else:
        answer = input("用户没有登录!是否重新登录(y/n)")
        if answer == 'y':
            username = input("用户名:")
            password = input("密码:")
            islogin = login(username, password)
        else:
            print("未登录,无法添加商品")

def login(username, password):
    if username == user and password == pwd:
        print("登录成功!")
        return True
    else:
        print('用户名或密码错误')
        return False

username = input("用户名:")
password = input("密码:")
islogin = login(username, password)
add_shoppingcart('电脑')

练习2:带验证码的用户登录

带验证码的用户登录(验证码和用户登录封装成两个函数)

user = 'admin'
pwd = '123'

def generate_checkcode(n):
    s = '1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM'
    code = ''
    for i in range(n):
        ran = random.randint(0, len(s))
        code += s[ran]
    return code

def login():
    username = input("用户名:")
    password = input("密码:")
    code = generate_checkcode(5)
    print("验证码是:", code)
    code1 = input("请输入验证码:")
    if code1.lower() == code.lower():
        if username == user and password == pwd:
            print("用户登录成功!")
        else:
            print("用户名或密码错误!")
    else:
        print("验证码错误!")

# 调用
login()
Last modification:August 8th, 2020 at 05:59 pm
如果觉得我的文章对你有用,请随意赞赏