• 函数


    位置函数:

        def  message(name,age,country,course):    ##这里括号内的参数即形参

            print(name)      ##print的括号内的参数为实参,即实际参与的参数

            print(age)

            print(country)

            print(course)

    默认参数:   

        def  message(name,age,course,country = 'cn'):    ###这里的country 为默认参数,即当输入参数的时候,如果不输入这个参数,就会输出默认值   

            print(name)           

            print(age)

            print(country)

            print(course)

        message('jack',19,'python',coujntry = 'uk' )    #country的输出就会变为'uk'

    关键参数:

        

        def  message(name,age,course = 'python',country = 'cn'):     ##输出时,按函数体内部顺序输出,无需在输入参数时顺序与之对应

            print(name)           

            print(age)

            print((course)

            print(country)

        message('jack',19,coujntry = 'uk' )    

    非固定参数:

        def message(*args):    ###当不确认要有多少参数的时候,就用 *args, 这时,无论输入多少参数,全都写进一个元祖里

            print(args)

         

    还有一种即**kwargs

        def message(**kwargs): 

            print(kwargs)

    meseage(name = 'jack',age = 18, country = 'cn')

    输出结果为:

    {name : 'jack',age : 18, country : 'cn'}   ##即**kwargs 传入的参数全都写进字典

    函数在没被调用前,不会运行

        age =  18    ##此处 赋值为18的age 为全局变量,全局变量即无论函数体内还是函数体外都可以调用,全局变量在函数体内无法修改,

        def  kk():    但全局变量只要不是字符串,数字,布尔值 就可以在函数体内修改,如列表内的元素,就可以修改

          age = 56   ##此处赋值为56的age 为局部变量,只能在函数体内调用  

          print(age)

          def hh():

            age = 76

            print(age)

    输出结果为 56

          name1 = [1,2,3,4]

          def  kk():

          name1[1] = 9

        kk()  ##此处记得要调用,要不就略过函数体了

        print(name1)

    内置函数:

        https://docs.python.org/3/library/functions.html?highlight=built#ascii

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

    #encoding:utf-8

    def kk(str1,number_int = 0,number_str = 0,number_space = 0,number_other = 0):
    for i in str1:
    if i.isdigit():
    number_int +=1 ##在这里得知,当循环一个字符串的时候,返回的每一项依旧为字符型

    elif i.isalpha() :
    number_str += 1

    elif i.isspace():
    number_space += 1

    else:
    number_other += 1

    print('int类型:%s str类型:%s space类型:%s other类型:%s ' % (number_int,number_str,number_space,number_other))
    kk('jack123 ,,')
  • 相关阅读:
    浮点数二分
    [模板]整数二分
    Mybatis实现增删改查
    如何使用 KEIL 下载 HEX 文件?
    线程CPU使用率该如何计算?
    单片机里面的CPU使用率是什么鬼?
    ASP.NET Core 3.1使用JWT认证Token授权 以及刷新Token
    ASP.NET Core 3.1使用Swagger API接口文档
    Visual Studio 默认git拉取Github出错 No error could not read Username for 'https://github.com': terminal prompts disabled
    ASP.NET Core 3.1使用log4net/nlog/Serilog记录日志
  • 原文地址:https://www.cnblogs.com/christmassa/p/9017220.html
Copyright © 2020-2023  润新知