python-函数,,python-函数1


python-函数


1、面向对象的定义是靠-类》》class
2、面向过程的定义是靠-过程 》》def
3、函数式编程的定义是靠-函数》》def

定义:函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段,同时也逻辑结构化和过程化的一种编程方法。

作用:函数能提高应用的模块性,和代码的重复利用率。
python函数的分类:内建函数和自定义函数
Python提供了许多内建函数,比如print()。
自己创建函数,这被叫做用户自定义函数

自定义函数语法定义

def text1(x): #定义函数名#算明的岁数 #解释函数x+=1print("how old are you next year %s:" %x)#打印你的名字return(x)#返回值x=text1(20)打印结果:how old are you next year 21:

函数的优势:

例1:重复利用

def test():    with open ("a.txt","a+") as f:       f.write("please give money\n ")def test1():    print("give to one")    test()def test2():    print("give to tow")    test()def test3():    print("give to three")    test()test1()test2()test3()

打印结果

give to one
give to tow
give to three

同时a文件中有

please give money
please give money
please give money

例2:可扩展性
import  timedef test():    time_format="%Y-%m-%d %X"    time_curent=time.strftime(time_format)    with open ("a.txt","a+") as f:      f.write("%s please give money\n " %time_curent)def test1():    print("give to one")    test()def test2():    print("give to tow")    test()def test3():    print("give to three")    test()test1()test2()test3()


打印结果

give to one
give to tow
give to three

a文件内容

2019-12-01 01:41:41 please give money
2019-12-01 01:41:41 please give money
2019-12-01 01:41:41 please give money




python-函数

评论关闭