Python 定义函数

2023-01-31 01:01:37 python 函数 定义

1.1   调用函数

要调用一个函数,需要知道函数的名称和参数。

abs绝对值函数

>>> abs(-10)

10

>>> abs(-213)

213

max最大值函数

>>> max(-1,2,5)

5

数据类型转换

>>> int(12.3)

12

>>> int('12.3')   --转换带有小数的整数字符串时,会报错

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

ValueError: invalid literal for int() witHBase 10: '12.3'

>>>int('12')    --转换不带有小数的整数字符串时,会报错

12

>>>int(float('12.3'))    --借助float函数可实现转换

12

>>> float('12.3')

12.3

>>> str(12.3)      --字符串函数

'12.3'

>>> str(100)

'100'

>>> bool(1)

True

>>> bool(0)

False

>>> bool('')

False

1.2   定义函数

python中,定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回。

def my_abs(x):

   if x >= 0:

       return x

   else:

       return –x

函数体内部的语句在执行时,一旦执行到return时,函数就执行完毕,并将结果返回。

如果没有return语句,函数执行完毕后也会返回结果,只是结果为None。

return None可以简写为return。

1.2.1   交互式环境中

>>> def my_abs(x):

...    if x>= 0:

...        return x

...    if x< 0:

...        return -x

...     –需要两次回车键

>>> my_abs(-1)

1

>>> my_abs(-8.1)

8.1

Python交互环境中定义函数时,注意Python会出现...的提示。函数定义结束后需要按两次回车重新回到>>>提示符下

1.2.2   非交互式环境

[root@daidai python]# vi my_abs.py

#!/usr/bin/python

# -*- coding:utf-8 -*-

def my_abs(x):

   if x >= 0:

       return x

   else:

       return –x

>>> from my_abs import my_abs    --第一个my_abs是py文件,第二个my_abs是函数

>>> my_abs(-1)

1

1.2.3   空函数

定义一个空函数

>>> def pop():

...    pass       --pass表示什么也不做,也可用于if判断中,和plsql中的null类似

...

>>> pop()

>>> 

1.2.4   参数检查

升级my_abs函数,对输入参数进行检查

>>> def my_abs1(x):

...    if not isinstance (x,(int,float)):            -- isinstance用于数据检查

...        raise TypeError('Bad oprand type')

...    if x >=0:

...        print(x)

...    if x <0:

...        print(-x)

...

>>>

>>> my_abs1('Y')

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

 File "<stdin>", line 3, in my_abs1

TypeError: Bad oprand type

1.2.5   函数返回多个值

[root@daidai python]# cat move.py

#!/usr/bin/python

# -*- coding:utf-8 -*-

 

import math

def move(x,y,step,angle=0):

   nx = x + step * math.cos(angle)

   ny = y + step * math.sin(angle)

return nx, ny

>>> import math

>>> t=move(100, 100, 60,math.pi/6)

>>> print(t)

(151.96152422706632, 130.0)    --本质上,返回的是一个tuple

>>> x, y = move(100, 100, 60,math.pi/6)   --多个变量按位置赋值

>>> print(x, y)

151.96152422706632 130.0


相关文章