python定义x_Python 定义函数(示例代码)
1函數
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 "", line 1, in
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非交互式環境
[[email?protected] 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 "", line 1, in
File "", line 3, in my_abs1
TypeError: Bad oprand type
1.2.5函數返回多個值
[[email?protected] 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
總結
以上是生活随笔為你收集整理的python定义x_Python 定义函数(示例代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 宽带改了路由器怎么设置家里的网络换路由器
- 下一篇: 115 亿,零跑汽车牵手玛莎拉蒂母公司