Python 函式學習(一)

2022-06-09 18:15:09 字數 1860 閱讀 5151

描述:isinstance()函式來判斷乙個物件是否是乙個已知的型別,類似type()。

isinstance()與type()區別:

如果要判斷兩個型別是否相同推薦使用isinstance()

語法:以下是isinstance方法的語法:

isinstance(object,classinfo)

引數

返回值:如果物件的型別與引數二的型別(classinfo)相同則返回true,否則返回false。

例項

以下展示了使用instance函式的例項:

1 >>>a = 2

2 >>>is

instance(a, int)

3true

45 >>>is

instance(a, str)

6false

78 >>>isinstance(a,(str, int,list)) #

是元祖中的乙個返回true

9 true

輸入:

>>>str = 'hello'

>>>isinstance(a, str)

報錯資訊:typeerror: isinstance() arg 2 must be a type or tuple of types

出錯產生的原因是因為我們在練習**的時候對str進行的賦值,導致了hello這個字串比較的時候報錯

解決辦法:重啟idle,不要對str型別進行賦值,問題解決

描述:cmp()函式用於比較2個物件,如果xy返回1

語法:以下是cmp()方法的語法

cmp(x,y)

引數:

返回值:如果xy返回1

例項

以下展示了使用cmp()函式的例項:

>>> a = [1, 2, 3] 

>>> b = [4, 5, 6]

>>> cmp(a, b)

在python3中無法使用cmp()函式,否則報以下錯誤:

下面講解在python3中使用operator模組實現同樣的功能。

描述:python3中使用operator模組進行字串、數字兩個變數的大小比較;在使用operator模組時需要先導入該模組,使用命令import operator來進行匯入。

語法:

operator.eq(x,y)

operator.ne(x,y)

operator.lt(x,y)

引數:eq(x,y) --相等判斷

ne(x,y) --不等判斷

lt(x,y) --大小判斷

常用對照速查表:

python 函式學習

今兒再網上看了下別人總結的python 函式,功能挺強大的,c有的功能都有,下面就記些它的功能點 1 定義,格式跟c不一樣,概念是一樣的。def 函式名 引數列表 函式語句 return 返回值 2 函式可以命別名,很方便啊,c語言我記憶中只有指標可以。def sum list result 0 f...

Python函式學習

def hello name return hello,name print hello holly defhello name print hello,name hello holly 輸出結果為hello,holly!稍微複雜一點的例子有 求長方體的體積 def volume length,wi...

Python函式學習

1 def 語句和引數 def hello name print hello name hello alice hello bob 如果執行這個程式,輸出看起來像這樣 hello alice hello bob 在這個程式的 hello 函式定義中,有乙個名為 name 的變元 變元 是乙個 變數,...