Python學習篇 之 基礎知識點

2021-08-07 16:39:14 字數 1824 閱讀 3212

假設有字串物件x

(1) type()函式

print(type(x))

#得到:

(2)_ _class_ _屬性

print(x.__class__)

#得到:

(3)isinstance()函式

isinstance()函式返回值為bool型別

a = 'haha';

print(type(a))

if(isinstance(a,str)):

print(true)

else:

print(false)

注意:使用isinstance(obj,str)時,前面的**不要出現以str為名稱的變數,否則會出現錯誤:

"typeerror: isinstance() arg 2 must be a type or tuple of types"

補充:type()和isinstance()的區別:

對具有繼承關係的類,type()不能判斷出是否是父類。

舉例說明:

class a:

pass

class b(a):

pass

#輸出為true

if(type(a()) == a):

print(true)

else:

print(false)

#輸出為true

if(isinstance(a(),a)):

print(true)

else:

print(false)

#輸出為false

if(type(b()) == a):

print(true)

else:

print(false)

#輸出為true

if(isinstance(b(),a)):

print(true)

else:

print(false)

執行結果如下:

true

true

false

true

其中,a是b的父類,用type() 判斷b的物件是否是a型別時,出現錯誤,即說明type()不能判斷父型別。

a = 1;

if a == 1:

print("first")

elif a == 2 :

print("second")

else:

print("none")

不同點:else if 變為 elif

count = 2

while count < 5 :

pass

else:

print("circle end")

while  ... else ...在迴圈語句結束時執行else語句塊。

#法1:直接遍歷

for sentence in list:

print(sentence)

else:

print("end")

#法2:通過索引遍歷

list = ['one','two','three','four','five']

for index in range(len(list)):

print(list[index])

else:

print("end")

Python基礎知識點

python2與python3編碼相容性 python2如果沒有指定編碼格式,預設的編碼是ascii,不進行轉換會出現unicodedecodeerror錯誤,為了使得python2與3進行相容,可以用如下 實現 import sys from django.utils import six if ...

python基礎知識點概括

1.1.1 輸出 print 要輸出的內容 加引號,就是按照字串的格式輸出,否則就是計算之後輸出,如果要格式化輸出的話,用 隔開 1.1.2 輸入 input 提示資訊 raw input t提示資訊 都可以,讀取的內容都是字串形式,有些時候,就需要將讀取的字串轉為整數,使用int 來轉換 1.2....

Python基礎知識點(一)

編寫程式需要使用注釋,一般以 開頭 單行注釋以 開頭 多行注釋 內容 中文支援以 conding utf 8 變數 用於儲存資料 變數型別 數字型別 布林型別 true,false 字串型別 列表型別 元組型別 字典型別 檢視型別 type 變數名 1 標示符 由字母,下劃線,數字組成 且數字不能開...