python学习2-1

一、.定义函数
1.
1.1 def 函数名(参数):
XXXXXXXXXX
return xxxxxx
例如:
def my_abs(x):
if x>=0:
return x
else:
return -x
1.2 如果把my_abs()函数保存成abstest.py文件
用 from abstest.py import my_abs 来导入my_abs()函数
例如: from abstest.py import my_abs
my_abs(-10)
1.3 定义空函数
def 函数名(参数):
pass
1.4 isinstance()数据类型检查函数
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError(‘错误的参数类型’)
if x>=0:
return x
else:
return -x
1.5 函数可以返回多个值
import math
def move(x,y,step,angle=0)
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
x, y = move(100, 100, 60, math.pi / 6)
print(x, y)
r = move(100, 100, 60, math.pi / 6)
print®
可以看出返回值是一个tuple!但是,在语法上,返回一个tuple可以省略括号,而多个变量可以同时接收一个tuple,按位置赋给对应的值,所以,Python的函数返回多值其实就是返回一个tuple。
1.6 小结:
定义函数时,需要确定函数名和参数个数;
如果有必要,可以先对参数的数据类型做检查;
函数体内部可以用return随时返回函数结果;
函数执行完毕也没有return语句时,自动return None。
函数可以同时返回多个值,但其实就是一个tuple。
1.7 练习
请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:
ax^2 + bx + c = 0的两个解。
import math
def quadratic(a, b, c):
if not isinstance(a,(int,float)):
raise TypeError(‘a is not a number’)
if not isinstance(b,(int,float)):
raise TypeError(‘b is not a number’)
if not isinstance(c,(int,float)):
raise TypeError(‘c is not a number’)
d=bb-4a*c
if a0:
if b
0:
if c==0:
return ‘方程根为全体实数’
else:
return ‘方程无实根’
else:
x1=-c/b
x2=x1
return x1,x2
else:
if d<0:
return ‘方程无实根’
else:
x1 = (-b + math.sqrt(d))/2/a
x2 = (-b - math.sqrt(d))/2/a
return x1,x2
print(quadratic(2, 3, 1))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值