python之函数(一)

python有很多内置函数,可以直接调用。比如type(), len(), range(),max(), min(), filter().内置函数我们就先不多提,我们主要介绍自定义函数。

1. 函数的定义

函数的定义用def

def 函数名(参数1, 参数2, 参数3,......):

  函数体

  return 表达式


先来一个简单的函数:

1 def greet():
2     print("Hello world")
3 
4 greet()

这个函数没有参数,接下来记录一下有参数的情况。

2. 函数参数

 1 # def greet():
 2 #     print("Hello world")
 3 
 4 
 5 '''
 6 一个参数
 7 '''
 8 def sayHello(name):
 9     print("Hi, "+name)
10 
11 
12 '''
13 两个参数
14 '''
15 def greet(greet, name):
16     print(greet + "," + name)
17 
18 
19 sayHello("yosef")
20 greet("你好", "yosef")

关于函数传递,有两点需要注意:

1. 调用函数传入的参数一定要跟函数定义的参数个数一样,否则会报错

2.传入的参数要和定义函数时的数据类型要一致。

3.  默认参数

 如果我们在编写函数时,给函数形参一个默认值。在调用函数时,如果不传参,就使用默认的值;传了参数,就使用传的参数。

 1 #!/usr/bin/python3
 2 # -*- coding: utf-8 -*-
 3 # @Time     :2018/11/27 13:32
 4 # @Author   :yosef
 5 # @Email    :wurz529@foxmail.com
 6 # @File:    :class14.py
 7 # @Software :PyCharm Community Edition
 8 
 9 
10 def sayHello(name="visitor"):
11     print("hello "+name)
12 
13 
14 sayHello()
15 sayHello("Yosef")

接下来是几个例子:

 1 #!/usr/bin/python3
 2 # -*- coding: utf-8 -*-
 3 # @Time     :2018/11/27 13:32
 4 # @Author   :yosef
 5 # @Email    :wurz529@foxmail.com
 6 # @File:    :class14.py
 7 # @Software :PyCharm Community Edition
 8 
 9 
10 # def sayHello(name="visitor"):
11 #     print("hello "+name)
12 #
13 #
14 # sayHello()
15 # sayHello("Yosef")
16 
17 """
18 编写print_info()函数,打印一个句子,指出这一节学了什么,调用这个函数,确认打印显示的消息正确无误。
19 
20 """
21 def print_info():
22     print("我学习了函数!")
23 
24 
25 print_info()
26 
27 
28 """
29 编写favourite_book();
30 """
31 def favourite_book(bookname = "Linux从删库到跑路"):
32     print("我最喜欢的书是:"+bookname)
33 
34 favourite_book("Python从入门到放弃")
35 favourite_book()

4. 位置参数与默认参数

第三节说的是只有一个参数,如果有多个参数该怎么做呢?

假设一个函数叫sum(a, b=3,c=5),如果调用的时候sum(1);sum(1,2),sum(1,2,3)有什么效果呢

1 def sum(a,b=3,c=5):
2     print(a+b+c)
3 
4 sum(1)  # a=1 b=3 c=5
5 sum(1,2)  # a=1 b=2 c=5
6 sum(1,2,3) # a=1 b=2 c=3

当只传一个参数的时候,默认给第一个参数赋值。传2个就给前2个参数赋值,传N个就给前N个参数赋值。

如果我想给第二个以及第五个值传参,其他默认,该怎么搞呢?

假设abcde五个参数,abcde的默认值为1;可以sum(b=2,e=3)即可,直接声明参数以及值。

1 def sum(a=1,b=1,c=1,d=1,e=1):
2     print(a+b+c+d+e)
3 sum(b=2,e=5)

练习:

 1 #!/usr/bin/python3
 2 # -*- coding: utf-8 -*-
 3 # @Time     :2018/11/27 13:59
 4 # @Author   :yosef
 5 # @Email    :wurz529@foxmail.com
 6 # @File:    :class16.py
 7 # @Software :PyCharm Community Edition
 8 def make_shirt(size, words):
 9     print("T恤的size是%s,字样是'%s'" %(size,words))
10 
11 
12 make_shirt("xl","")
13 
14 
15 def describle_city(city="shanghai",country="China"):
16     print("%s is in %s" %(city,country))
17 
18 
19 describle_city()
20 describle_city("nanjing")
21 describle_city("beijing")
22 describle_city("北海道","日本")

原文地址:https://www.cnblogs.com/wlyhy/p/10025448.html