zoukankan      html  css  js  c++  java
  • python学习笔记4--函数/全局变量/递归

    一、函数是什么?

    函数一词来源于数学,但编程中的「函数」概念,与数学中的函数是有很大不同的,编程中的函数在英文中也有很多不同的叫法。在BASIC中叫做subroutine(子过程或子程序),在Pascal中叫做procedure(过程)和function,在C中只有function,在Java里面叫做method。

    定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可。

    二、使用函数的好处:

    1、简化代码
    2、提高代码的复用性
    3、代码可扩展

    三、python中函数的使用:

    1、定义函数使用def关键字,后面是函数名,函数名不能重复,然后执行调用

    def hello(file_name,content):  #形参
        f=open(file_name,'a+')
        f.seek(0)
        f.write(content)
        f.close()
        
    #调用函数
    hello('123.txt','hahhahha')  #实参
    

    2、默认值参数,调用时不是必填的

    #默认值参数:不是必填的
    def hello2(file_name,content=''):
        f=open(file_name,'a+')
        if content:
            f.seek(0)
            f.write(content)
        else:
            f.seek(0)
            res=f.read()
            return res
        f.close()
    
    hello2('123.txt')   #content 默认为空
    hello2('123.txt',content='12345')
    

    3、可变参数,不常用

    #可变参数
    #不常用
    def test3(a,b=1,*args): #可变参数 *args
        print('a',a)
        print('b',b)
        print('args',args)
    
    test3(2,3,'ahahha','hahhaha3','hahhaha4')

    4、关键字参数,传入是一个dict

    #关键字参数
    def test4(**kwargs):
        print(kwargs)
    test4(name='suki',sex='man')   #传参是dic形式

    四、函数的返回值

    def calc(x,y):#这个就是定义了一个有返回值的函数
        c = x*y
        return c,x,y
    res = calc(5,6)#把函数的返回结果赋值给res
    print(res)
    #函数返回值return
    #需要获取结果必须return,可以没有返回值
    #return:立即结束函数
    user=hello2('13.txt')
    print(user) 

    五、全局变量和局部变量

    a=100 #全局变量
    def test2():
        global a   #声明全局变量 才能修改a的值
        a=5
        print('里面的',a)
    test()
    print('外面的',a)  

    六、函数的递归

    #递归
    #自己调用自己,函数的循环
    
    def test1():
        num = int(input('please enter a number:'))
        if num%2==0:#判断输入的数字是不是偶数
           return True #如果是偶数的话,程序就退出了,返回true
        print('不是偶数请重新输入!')
        return test1()#如果不是偶数的话继续调用自己,输入值
    print(test1())#调用test

      

      

  • 相关阅读:
    listview item 动画
    android sqlite blob
    Python3 配置文件(configparser)(转载)
    python之字符串格式化(format)
    PHP模拟发送POST请求之一、HTTP协议头部解析
    用HTML/JS/PHP方式实现页面延时跳转
    用memoization优化递归算法[JS/PHP实现]
    开通博客,记录一下。
    SpringMvc Json LocalDateTime 互转,form urlencoded @ModelAttribute 转换
    Springdata mongodb 版本兼容 引起 Error [The 'cursor' option is required, except for aggregate with the explain argument
  • 原文地址:https://www.cnblogs.com/SuKiWX/p/8945907.html
Copyright © 2011-2022 走看看