• 十一、python函数学习


    1.    定义函数

    def   函数名(形参):

        函数体

        return  xxx--------其下面的内容不再执行

    ---------------------------------------------------------------------------------------------------------------

    2.执行函数

          函数名(实参)

    ---------------------------------------------------------------------------------------------------------------

    3.形参,实参(默认按照顺序)

    ---------------------------------------------------------------------------------------------------------------

    4.执行形参传入实参,可不按照顺序

    ---------------------------------------------------------------------------------------------------------------

    5.函数可以有默认参数

    ---------------------------------------------------------------------------------------------------------------

    6.动态参数  
    #动态参数一,类型为元祖,传的参数为元祖的元素
    def f1(*a):
    print (a,type(a))
    f1(123,234,[456123789],{1:2})
    #动态参数二,类型为字典,传入的参数为字典的键值对
    def f1(**a):
    print (a,type(a))
    f1(k1=123,k2=456)
    #万能动态参数-------一*较**在前
    def f1(*a,**p):
    print (a,type(a),type(p))
    f1(123,234,[456123789],{1:2},k1=123,k2=456)
    ---------------------

        ((123, 234, [456123789], {1: 2}), <type 'tuple'>)
        ({'k2': 456, 'k1': 123}, <type 'dict'>)
        ((123, 234, [456123789], {1: 2}), <type 'tuple'>, <type 'dict'>)

    ---------------------------------------------------------------------------------------------------------------

    7.为动态参数传入字典,列表

    def f1(*args):
    print (args,type(args))
    l1=[11,22,33,44]
    f1(l1)
    f1(*l1)
    ------------------------

     (([11, 22, 33, 44],), <type 'tuple'>)
     ((11, 22, 33, 44), <type 'tuple'>)

    ------------------------

    def f2(**args):
    print (args,type(args))
    l1={"k1":"123"}
    f2(l1=l1)
    f2(**l1)
    -------------------------

       ({'l1': {'k1': '123'}}, <type 'dict'>)
       ({'k1': '123'}, <type 'dict'>)

    ---------------------------------------------------------------------------------------------------------------

    8.全局变量,局部变量

    P="chushujin"
    def func1():
    #局部变量
    a=123
    global P #加上此关键词后,全局变量就会被修改,否则不会被修改
    print (a)
    P="zhangyu"
    def func2():
    print (P)
    func1()
    func2()
    ----------------------

       123
     zhangyu

    ---------------------------------------------------------------------------------------------------------------

    9.lambda表达式

    def f1():
    return 123
    f2=lambda : 123

    print f1()
    print f2

    def f3(a1,a2):
    return a1+a2
    f4=lambda a1,a2:a1+a2

    print f3(1,2)
    print f4(2,3)
    ----------------------

        123
        <function <lambda> at 0x00000000026A2BA8>
        3
        5

    ---------------------------------------------------------------------------------------------------------------

    10.文件操作open
    打开文件:open("文件名/文件路径",模式,编码)
    操作文件
    关闭文件
    '''
    close(),flush(),read(),readline(),seek(),tell(),truncate(),write(),
    '''
    '''
    # f=open("hello.log","r") #默认不写为只读
    # data=f.read()
    # print data
    # f.close()

    #只读 r---不可写
    # f=open("hello.log","r") #默认不写为只读
    # data=f.write()-------------报错
    # f.close()

    #只写 w---不可读
    # f=open("hello.log","w") #默认只写不可读
    # data=f.write("123") #-------------报错
    # f.close()

    #a,追加模式【不可读; 不存在则创建;存在则只追加内容;】
    f=open("hello.log","a")
    f.write("aaa")
    data=f.read()
    print data
    f.close()

    #x, 只写模式【不可读;不存在则创建,存在则报错】-----py3
    f=open("hello.log","x")
    f=open("hello2.log","x")
    f.write("aaa")
    ==================================================================
    二进制方式打开:
    #二进制的方式打开
    #只读
    # f=open("hello.log","rb")
    # data=f.read()
    # print (data)
    # print (str(data,encoding="utf-8"))
    --------------------------------------

     b'xe4xb8xadxe5x9bxbd'
        中国

    --------------------------------------
    #只写
    # f=open("hello.log","wb")
    # f.write(bytes("中国",encoding="utf-8"))
    ==================================================================
    '''
    r+:读写【可读,可写】
    w+:写读【可读,可写】
    x+:写读【可读,可写】
    a+:写读【可读,可写】
    '''
    #r+:打开文件,write:末尾追加内容,指针末尾,如果读取时的指在某一位置,写的时候只会在末尾
    #tell():显示指针的位置
    #feek(x):调整指针的位置
    f=open("hello.log","r+",encoding="utf-8")
    print (f.tell()) #指针的位置,一个汉字3个字节
    data=f.read(1)
    print (f.tell())
    print (type(data),data)
    print (f.tell())
    data=f.read(1)
    print (f.tell())
    print (type(data),data)
    f.seek(3)
    print (f.tell())
    --------------------------

     0
        3
        <class 'str'> 中
        3
        6
        <class 'str'> 国
        3

    --------------------------
    # f.write("中国")
    # data=f.read()
    # print (type(data),data)
    f.close()
    --------------------------
    #a+:写读【可读,可写】:打开的同时指针已经在末尾
    f=open("hello.log","a+",encoding="utf-8")
    print (f.tell())
    f.seek(0)
    data=f.read()
    print (data)
    f.write("QA")
    --------------------------
    #w+:写读【可读,可写】:先清空,再写之后就可以读了
    #只要写入内容,指针调至最后
    f=open("hello.log","w+",encoding="utf-8")
    data=f.write("我们")
    f.seek(0)
    data=f.read()
    print (data)
    f.close()
    ================================================================
    '''
    readline():只读取一行
    '''
    # f=open("hello.log","r+",encoding="utf-8")
    # data=f.readline()
    # print (data)

    readlines:读取多行
    ['第一行','第二行'...]
    '''
    truncate():截断数据,仅保留指定之前数据
    '''
    # f=open("hello.log","r+",encoding="utf-8")
    # print (f.tell())
    # data=f.read()
    # print (data)
    # f.seek(6)
    # f.truncate()
    # f.close()

    f=open("hello.log","r",encoding="utf-8")

    #f.read()

    for line in f:
    print (line)
    ==============================================================
    '''
    关闭:close()相当于with open("xxx","r",encoding="utf-8") as f
    自动关闭文件
    '''
    # with open("hello.log","r",encoding="utf-8") as f:
    # # data=f.read()
    # # print (data)


    '''
    同时打开两个文件,将第一个文件中的数据一行一行写入第二个文件
    with open("源文件","r",encoding="utf-8") as f1,open("新文件","w",encoding="utf-8") as f2:
    '''
    with open("hello.log","r",encoding="utf-8") as f1,open("hello2.log","w",encoding="utf-8") as f2:
    for line in f1:
    f2.write(line)

    ---------------------------------------------------------------------------------------------------------------
    11.注册登录函数
    
    
    def login(username,password):
    '''
    用于用户名密码的验证
    :param username: 用户名
    :param password: 密码
    :return: True,用户验证成功;False,用户验证失败
    '''
    with open('db', encoding='utf-8') as f:
    ret = []
    for i in f:
    i = i.strip() # 去除首尾的空格和换行符
    m = i.split('$') # 通过指定的分隔符对字符串进行切片
    if username == m[0] and password == m[1]:
    #print("登录成功")
    #break
    return True
    return False

    def register(username,password):
    '''
    注册用户:
    1.打开文件,追加a
    2.用户名$密码
    :param username:
    :param password:
    :return:
    '''
    with open("db","a",encoding="utf-8") as f:
    temp=" "+username+"$"+password
    f.write(temp)
    return True

    def user_exist(username):
    '''
    一行一行的查询,如果用户名存在返回true 不存在返回false
    :param username: 用户名
    :return: true用户名存在,false用户名不存在
    '''
    with open('db',"r",encoding="utf-8") as f:
    for line in f:
    line=line.strip()
    line_list=line.split("$")
    if line_list[0]==username:
    return True
    return False

    def main():
    print ("欢迎登录xxxx系统")
    inp=input("1:登录,2:注册")
    if inp=='1':
    user = input("请输入用户名:")
    passwd=input("请输入密码:")
    is_login=login(user,passwd)
    if is_login:
    print ("登录成功")
    else:
    print ("登录失败")
    elif inp=='2':
    user = input("请输入用户名:")
    passwd = input("请输入密码:")
    is_exist=user_exist(user)
    if is_exist:
    print ("用户名已存在,请直接登录")
    else:
    print ("用户名不存在,请注册")
    result=register(user,passwd)
    if result:
    print ("注册成功")
    else:
    print ("注册失败")

    main()
  • 相关阅读:
    SQLite增删改查(自己写SQL语句)
    Why you have so few friends?
    android数据库SQLite简单测试
    C语言 stringcpy,stringcat,stringcmp实现
    python 日期和时间
    Python continue 语句
    Python break 语句
    Python 循环语句
    Python 条件语句
    Python比较运算符
  • 原文地址:https://www.cnblogs.com/chushujin/p/9350874.html
Copyright © 2020-2023  润新知