python-函数1(定义-作用-优势-返回值)

python-函数1(定义-作用-优势-返回值)


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

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

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

自定义函数语法定义

def text1(x): #定义函数名
#算明的岁数 #解释函数
x+=1
print("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
 ")
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  time
def 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
 " %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
#返回值
例1:
def test1():
    print("in the test1")
    return 0
    print("in the test2")
x=test1()  #将函数的返回值,赋值给x
print(x)

打印结果

in the test1
0






例2:
def test1():
    print("in the test1")
# return 0
def test2():
    print("in the test2")
    return 0
def test3():
    print ("in the test3")
    return 1,'hello',["KEZI","KKKGUI"],{"NAME":"HK"},test2,test2() #数字,字符串,列表,字典,函数名(返回这个函数名的内存地址),函数值。

x=test1()
y=test2()
z=test3()
print(x)
print(y)
print(z)
  
打印结果
in the test1
in the test2
in the test3
None
0
(1, 'hello', ['KEZI', 'KKKGUI'], {'NAME': 'HK'}, <function test2 at 0x000001F7188A0268>, 0) #放到元组中进行返回, 。


总结:1:没有return ,或者没有传参,返回none
      2: 有一个返回值的,返回这个对象值。
      3:返回两个以上值,将返回的值放到元组中。
      4:返回值,也可以设置成 return test1() 
      



原文地址:https://www.cnblogs.com/kezi/p/11964854.html