Day3-Python基础3---函数介绍

一、函数基本语法及特性

函数是什么?

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

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

特性:

  1. 减少重复代码
  2. 使程序变的可扩展
  3. 使程序变得易维护

语法定义

1 def #定义函数的关键字
2 test #函数名
3 () #定义形参,我这边没有定义。如果定义的话,可以写成:def test(x): 其中x就是形式参数
4 "the funcation details" # 文档描述(非必要,但是强烈建议你为你的函数添加详细信息,方便别人阅读)
5 print #泛指代码块或者程序逻辑处理
6 return #定义返回值
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:Ma Qing
 4 
 5 def name():   #def后面的是函数名称
 6     print("今天是星期二!")
 7    return 0
 8 for i in range(10):
 9     print("----打印的是上面的函数-----")
10     name()    #调用函数的方式

函数还可以带参数

 1 #下面这段代码
 2 a,b = 2,3
 3 c = a**b
 4 print(c)
 5 
 6 #改成用函数写
 7 
 8 def calc(x,y):
 9     res = x**y
10     return res    #返回函数执行的结果
11 c = calc(a,b)
12 print(c)

函数定义

1 #函数式编程
2 def function():
3     """testing"""
4     print("in the func1")
5     return 0

过程定义

1 #面向过程
2 def function2():
3     """testing2"""
4     print("in the func2")

两者的输出对比

 1  1 x = function()
 2  2 y = function2()
 3  3 print(x)
 4  4 print(y)
 5  5  
 6  6 #输出
 7  7 in the test fun1
 8  8 in the test fun2
 9  9 #输出返回值
10 10 0
11 11 #没有return ,返回为空
12 12 None

举例说明使用函数的好处

1、代码的重复利用

2、可扩展性

3、保持一致性

下面代码是执行一个重复写入文件的过程

 1 import time      #时间函数
 2 def function():
 3     time_format = '%Y-%m-%d %X'
 4     time_current = time.strftime(time_format)
 5     with open('a.txt','a+') as f:
 6         f.write("%s Learnint Python
" %time_current)
 7 def test1():
 8     print("in the test1")
 9     function()
10 def test2():
11     print("in the test2")
12     function()
13     return 0
14 def test3():
15     print("in the test3")
16     function()
17     return 1,'hello',["maqing","peilin"],{'name':'maqing'}
18 
19 x = test1()
20 y = test2()
21 z = test3()
22 print(x)
23 print(y)
24 print(z)    #python返回值也是唯一。多结果以元组的方式返回
原文地址:https://www.cnblogs.com/bldly1989/p/6548909.html