一、调用函数
在交互式命令行通过help(abs)
查看abs
函数的帮助信息
把函数名赋给一个变量
a = abs
二、定义函数
求解方程:ax2 + bx + c = 0
1 # -*- coding: utf-8 -*-
2
3 import math
4
5 def quadratic(a, b, c):
6 n = b*b - 4*a*c
7 if n < 0:
8 return ("此方程无解")
9 elif n == 0:
10 return b/2*a
11 else:
12 x1 = (-b + math.sqrt(n))/(2*a)
13 x2 = (-b - math.sqrt(n))/(2*a)
14 return x1,x2
15
16 # 测试:
17 print(quadratic(1,2,1))
18 print(quadratic(4,2,2))
19
20
21 # print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
22 # print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))
23 # if quadratic(2, 3, 1) != (-0.5, -1.0):
24 # print('测试失败')
25 # elif quadratic(1, 3, -4) != (1.0, -4.0):
26 # print('测试失败')
27 # else:
28 # print('测试成功')
三、函数的参数