python定义x_Python 定义函数(示例代码)
1函數(shù)
1.1調(diào)用函數(shù)
要調(diào)用一個函數(shù),需要知道函數(shù)的名稱和參數(shù)。
abs絕對值函數(shù)
>>> abs(-10)
10
>>> abs(-213)
213
max最大值函數(shù)
>>> max(-1,2,5)
5
數(shù)據(jù)類型轉(zhuǎn)換
>>> int(12.3)
12
>>> int(‘12.3‘) --轉(zhuǎn)換帶有小數(shù)的整數(shù)字符串時,會報錯
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() withbase 10: ‘12.3‘
>>>int(‘12‘) --轉(zhuǎn)換不帶有小數(shù)的整數(shù)字符串時,會報錯
12
>>>int(float(‘12.3‘)) --借助float函數(shù)可實現(xiàn)轉(zhuǎn)換
12
>>> float(‘12.3‘)
12.3
>>> str(12.3) --字符串函數(shù)
‘12.3‘
>>> str(100)
‘100‘
>>> bool(1)
True
>>> bool(0)
False
>>> bool(‘‘)
False
1.2定義函數(shù)
在Python中,定義一個函數(shù)要使用def語句,依次寫出函數(shù)名、括號、括號中的參數(shù)和冒號:,然后,在縮進塊中編寫函數(shù)體,函數(shù)的返回值用return語句返回。
def my_abs(x):
if x >= 0:
return x
else:
return –x
函數(shù)體內(nèi)部的語句在執(zhí)行時,一旦執(zhí)行到return時,函數(shù)就執(zhí)行完畢,并將結(jié)果返回。
如果沒有return語句,函數(shù)執(zhí)行完畢后也會返回結(jié)果,只是結(jié)果為None。
return None可以簡寫為return。
1.2.1交互式環(huán)境中
>>> 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交互環(huán)境中定義函數(shù)時,注意Python會出現(xiàn)...的提示。函數(shù)定義結(jié)束后需要按兩次回車重新回到>>>提示符下
1.2.2非交互式環(huán)境
[[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是函數(shù)
>>> my_abs(-1)
1
1.2.3空函數(shù)
定義一個空函數(shù)
>>> def pop():
... pass --pass表示什么也不做,也可用于if判斷中,和plsql中的null類似
...
>>> pop()
>>>
1.2.4參數(shù)檢查
升級my_abs函數(shù),對輸入?yún)?shù)進行檢查
>>> def my_abs1(x):
... if not isinstance (x,(int,float)): -- isinstance用于數(shù)據(jù)檢查
... 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函數(shù)返回多個值
[[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) --本質(zhì)上,返回的是一個tuple
>>> x, y = move(100, 100, 60,math.pi/6) --多個變量按位置賦值
>>> print(x, y)
151.96152422706632 130.0
總結(jié)
以上是生活随笔為你收集整理的python定义x_Python 定义函数(示例代码)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 宽带改了路由器怎么设置家里的网络换路由器
- 下一篇: 115 亿,零跑汽车牵手玛莎拉蒂母公司