Python基礎數據類型


一、Python基本數據類型

  類型:

    1.數字類型:int(整形)、 float(浮點型)                    ####   int:age=int(10) long(長整形):a=(2**60)    注意:在python3里不再有long 類型了,全是int

    2.字符串類型: str(字符串)

    3.列表類型:list(列表)     

      在[]內用逗號分隔,可以存放n個任意類型的值。索引對應值,索引從0開始,0代表第一個  

students=['aaa','bbb','ccc',]         #students=list(['egon','alex','wupeiqi',])

>>> students_info=[['aaa',18,['play',]],['bbb',18,['play','sleep']]]
>>> students_info[0][2][0] #取出第一個學生的第一個愛好
'play'

    4.字典類型:dict(字典)  

#在{}內用逗號分隔,可以存放多個key:value的值,  key與value一一對應,比較時只比較第一個key, value可以是任意類型
定義:dict={'name':'aaa','age':18,'sex':18}        #dict=dict({'name':'egon','age':18,'sex':18})
用於標識:存儲多個值的情況,每個值都有唯一一個對應的key,可以更為方便高效地取值

 

    5.布爾值:bool(布爾值)

      判斷條件是真是假,是真返回True,是假返回False

  運算符:

    算術運算符

+  -  *  / (加減乘除)   %(取模即取余)   ** 冪運算:2**3=2的3次方=8         //  取整運算,取商的整數部分

    比較運算符

== 等於   !=不等於   >大於 < 小於     <= 小於等於  >= 大於等於  

    賦值運算符

賦值包括:鏈式賦值和交叉式賦值
a=b=1(鏈式賦值)       a,b=b,a (交叉賦值)       

    邏輯運算符

與或非(and    or     not
# 一:not、and、or的基本使用
# not:就是把緊跟其后的那個條件結果取反且not與緊跟其后的那個條件是一個不可分割的整體
# print(not 16 > 13)
# print(not True)
# print(not False)
# print(not 10)
# print(not 0)
# print(not None)
# print(not '')
 
# and:邏輯與,and用來鏈接左右兩個條件,兩個條件同時為True,最終結果才為真
print(True and 10 > 3)
 
print(True and 10 > 3 and 10 and 0) # 條件全為真,最終結果才為True
print( 10 > 3 and 10 and 0 and 1 > 3 and 4 == 4 and 3 != 3)  # 偷懶原則
 
# or:邏輯或,or用來鏈接左右兩個條件,兩個條件但凡有一個為True,最終結果就為True, 兩個條件都為False的情況下,最終結果才為False
print(3 > 2 or 0)
print(3 > 4 or False or 3 != 2 or 3 > 2 or True) # 偷懶原則
 
# 二:優先級not>and>or
# 如果單獨就只是一串and鏈接,或者說單獨就只是一串or鏈接,按照從左到右的順訊依次運算即可(偷懶原則)。如果是混用,則需要考慮優先級了
 
# res=3>4 and not 4>3 or 1==3 and 'x' == 'x' or 3 >3
# print(res)
# #       False                 False              False
# res=(3>4 and (not 4>3)) or (1==3 and 'x' == 'x') or 3 >3
# print(res)
 
 
 
res=3>4 and ((not 4>3) or 1==3) and ('x' == 'x' or 3 >3)
print(res)

 

  格式化輸出

    程序中經常會有這樣場景:要求用戶輸入信息,然后打印成固定的格式。占位符:%s(字符串占位符:可以接收字符串,也可接收數字)     %d(數字占位符:只能接收數字) 

#%s的使用
print('My name is %s,my age is %s' %('aaa',18))
>>>My name is aaa,my age is 18

#%d的使用
print('My name is %s,my age is %d' %('egon',18))
>>>My name is aaa,my age is 18

print('My name is %s,my age is %d' %('egon','18')) 
#報錯

    以字典形式傳值,可以不考慮位置

res = "my name is %(name)s, my age is %(age)s"%{"age":18,"name":"aaa"}
print(res)

    str.format:兼容性好

#按照位置傳值
res = "my name is {}, my age is {}".format('aaa',18)
print(res)

#不按照位置
res = "my name is {name}, my age is {age}".format("age":18,"name":"aaa")
print(res)

  賦值解壓   

    解壓賦值可以用在任何可迭代對象上。用下划線和*號在字符串或列表中占據不想取出的值,把多余的省略掉

#字符串解壓
>>> str_="beter"
>>> a_,b_,c_,d_,e_=str_
>>> a
_'b'
>>> b
_'e'
>>> c
_'t'
>>> d
_'e'
>>> e
_'r'
 
#列表解壓
>>> list_=["bet","tr"]
​
>>> la_,lb_=list_
​
>>> la_
​
'bet'>>> lb_
​
'tr'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM