基础函数的运用
>>> abs(-199)
199
>>> abs(200,100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (2 given)
>>> abs('abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
>>> max(-100.3,200,3.5)
200
>>> min(-100.3,200,3.5)
-100.3
>>> int('123')
123
>>> int('12.9')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.9'
>>> int('12.34')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.34'
>>> int(12.34)
12
2.自定义函数
预留问题
zhengyoncongdeMacBook-Pro:python zhengyoncong$ cat my_abs.py
#! /usr/bin/env
def my_abs(x)
if(x>0):
return x
else:
return -x
print(my_abs(-99))
运行结果:
zhengyoncongdeMacBook-Pro:python zhengyoncong$ ./myabs.py
99
但如果输入参数非整数,报错:
zhengyoncongdeMacBook-Pro:python zhengyoncong$ ./myabs.py
Traceback (most recent call last):
File "./myabs.py", line 8, in <module>
print(my_abs('hhh'))
File "./myabs.py", line 4, in my_abs
if(x>0):
TypeError: '>' not supported between instances of 'str' and 'int'
直接调用内置函数abs(),输入字符参数,则会抛出异常
>>> abs('hheh')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
解决办法:在自定义函数时添加参数检查,如果传入错误的参数类型,则抛出异常
#! /usr/bin/env python3
def my_abs(x):
if not isinstance(x,(int ,float)):
raise TypeError('bad operand type')
if(x>0):
return x
else:
return -x
print(my_abs('hhh'))
运行结果:
zhengyoncongdeMacBook-Pro:python zhengyoncong$ ./myabs.py
Traceback (most recent call last):
File "./myabs.py", line 11, in <module>
print(my_abs('hhh'))
File "./myabs.py", line 6, in my_abs
raise TypeError('bad operand type')
TypeError: bad operand type
多返回值
import math(必须放置在文件开头,不能放置在注释语句或其他语句之后)
def move(x,y,step,angle=0):
nx = x + math.cos(angle)*step
ny = y - math.sin(angle)*step
return nx,ny
#连个返回值
x,y = move(100,100,60,math.pi/6)
print(x,y)
#一个返回值
z=move(100,100,60,math.pi/6)
print(z)
运行结果:
zhengyoncongdeMacBook-Pro:python zhengyoncong$ ./myabs.py
151.96152422706632 70.0
(151.96152422706632, 70.0)
结果解释:
返回的是一个元组,多返回值的也是同一个值元组,只不过是按位置分配相应的值(多返回值接受的变量与多返回值的个数应该与之对应,否则会报错)
如:在最后添加一组三个变量接受返回值
a,b,c = move(100,100,60,math.pi/6)
print(a,b,c)
报错显示:
zhengyoncongdeMacBook-Pro:python zhengyoncong$ ./myabs.py
151.96152422706632 70.0
(151.96152422706632, 70.0)
Traceback (most recent call last):
File "./myabs.py", line 25, in <module>
a,b,c = move(100,100,60,math.pi/6)
ValueError: not enough values to unpack (expected 3, got 2)
总结:
自定义函数使用时,要注意函数参数个数及类型,不符合则会报错或抛异常。
函数可以有多个返回值,但实际只有返回值,返回值类型为元组。
定义函数时,函数体内部随时可用return返回,如果函数结束都没有return ,则默认返回None
函数体为空时,用pass占位。