Python学习札记(十一) Function2 函数定义

参考:定义函数

Note:

先看一段代码实例(Barefoot topo.py):

def read_topo():
    nb_hosts = 0
    nb_switches = 0
    links = []
    with open("topo.txt", "r") as f:
        line = f.readline()[:-1]
        w, nb_switches = line.split()
        assert(w == "switches")
        line = f.readline()[:-1]
        w, nb_hosts = line.split()
        assert(w == "hosts")
        for line in f:
            if not f: break
            a, b = line.split()
            links.append( (a, b) )
    return int(nb_hosts), int(nb_switches), links

函数功能是,打开topo.txt文件,根据文件内容确定host、switch、link数目,并返回。

函数调用处:

nb_hosts, nb_switches, links = read_topo()

1.Python中函数定义:def function_name() :

2.函数内部通过条件判断和循环可以实现非常复杂的逻辑。当遇到return语句,函数结束并返回参数。

3.可以通过from [name] import [function_name]导入函数,注意导入的文件后缀不加.py。

eg.

sh-3.2# more function1.py 
#!/usr/bin/env python3

def my_function(x) :
        if str(x) == 'Chen' :
                b = 'Good'
        elif str(x) == 'Li' :
                b = 'Better'
        else :
                b = 'Best'

        print(b)

        return b

sh-3.2# python3
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from function1 import my_function
>>> my_function('Chen')
Good
'Good'
>>> 

4.如果在一个判断语句中什么都不想做,则可以使用pass语句。

eg.

if age >= 18 :
    pass

5.参数检查。

如果传入的参数类型不对,Python解释器无法帮助我们解释。这个时候可以在函数中通过定义raise语句抛出错误,如:

eg.

def my_function(age, x) :

	if age < 0:
		raise RuntimeError('age < 0')
	else :
		pass

	if str(x) == 'Chen' :
		b = 'Good'
	elif str(x) == 'Li' :
		b = 'Better'
	else :
		b = 'Best'

	print(b)

	return b
>>> from function1 import my_function
>>> my_function(-1, 'Chen')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/wasdns/Desktop/PythonLearn/function1.py", line 6, in my_function
    raise RuntimeError('age < 0')
RuntimeError: age < 0
>>> 

也可以通过方法 isinstance() 进行参数类型检查:

def my_function(age, x) :

	if age < 0:
		raise RuntimeError('age < 0')
	else :
		pass

	if not isinstance(x, (str)) :
		raise TypeError('bad operand type') 
	else :
		pass
>>> from function1 import my_function
>>> my_function(1, 100)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/wasdns/Desktop/PythonLearn/function1.py", line 11, in my_function
    raise TypeError('bad operand type') 
TypeError: bad operand type
>>> 

6.函数返回多个值。Python的函数允许返回多个值,其本质是返回一个tuple。

在语法上,返回一个tuple可以省略括号,而多个变量可以同时接收一个tuple,按位置赋给对应的值,所以,Python的函数返回多值其实就是返回一个tuple,但写起来更方便。

练习:

请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:

ax2 + bx + c = 0

的两个解.

不考虑复数:

#!/usr/bin/env python3

import math

def quadratic(a, b, c) :

	q = b*b - 4*a*c

	if q > 0 :
		x1 = -b + math.sqrt(q)
		x2 = -b - math.sqrt(q)
		return x1/(2*a), x2/(2*a)
	else :
		print('No solutions')

2017/1/28

原文地址:https://www.cnblogs.com/qq952693358/p/6357390.html