Python基礎 - 02變數和資料型別
阿新 • • 發佈:2021-10-09
Python基礎 - 02變數和資料型別
一、命名規則
1.1 Python識別符號由字母、下劃線(_)和數字組成,且數字不能開頭。- 以下劃線開頭的識別符號是有特殊意義的,
- 以單下劃線開頭(_foo)的代表不能直接訪問的類屬性,需通過類提供的介面進行訪問,不能用"from xxx import *"而匯入。
- 以雙下劃線開頭的(__foo)代表類的私有成員,
- 以雙下劃線開頭和結尾的(__foo__)代表python裡特殊方法專用的標識,如__init__()代表類的建構函式。
and assert break class continue def del elif else except exec finally for from global if import in is lambda not or pass print raise return try while with yield
A = 100 b = 200 print(A) print(b) # 見名知意: getNameByLine # getNameByLine: 駝峰式:開頭第一個單詞全部小寫, 小駝峰式 # FilePath: 大駝峰式,面向物件的類名 getNameByLine = 'hello' get_name_by_line = 'world'
二、資料型別
2.1 基本的Python資料型別:整型(整數)、浮點數(帶小數點的數字)和字串。
- 數字型別: int(有符號整型)、long(長整型[也可以代表八進位制和十六進位制])、 float(浮點型)、complex(複數)
- 布林型別: True、 False
- 字串String
- 列表List
- 元祖Tuple
- 字典Dictionary
money = 28 print(type(money)) # <class 'int'> money = 28.9 print(type(money)) # <class 'float'> money = 0.96334321 print(money) # 0.96334321 print(type(money)) # <class 'float'> money = '100' print(type(money)) # <class 'str'> money = "100" print(type(money)) # <class 'str'> money = ''' 100 ''' print(type(money)) # <class 'str'> message = '微軟釋出: "Window 11來了"' print(message) # 微軟釋出: "Window 11來了" message = "微軟釋出: 'Window 11來了'" print(message) # 微軟釋出: 'Window 11來了' poem = ''' 靜夜思 唐李白 窗前明月光,疑是地上霜 舉頭望明月,低頭思故鄉 ''' print(poem) # 按照格式輸出 isLogin = True print(isLogin) # True isLogin = False print(isLogin) # False
2.2 資料型別轉換
userName = input('輸入姓名:') # 1
print(userName) # 1
print(type(userName)) # <class 'str'> , 所有輸入的都是字串型別。
total = input("輸入數量:")
print(total)
# TypeError: can only concatenate str (not "int") to str
# print(total + 19)
print(total+'19') # 1119, 字串拼接
print(int(total)+19) # 30, int型別相加
one = '19'
two = "110"
# str --> int / str --> float
print(int(one) + int(two)) # 129
print(float(one) + float(two)) # 129.0
print(int(one) - int(two)) # -91
print(float(one) - float(two)) # -91.0
# float --> int
a = 9.49
print(int(a)) # 9 , 小數點後的部分被去掉
# str --> int str必須是整數型別的字串,float格式的字串轉int 報錯
b = "9.49"
# ValueError: invalid literal for int() with base 10: '9.49'
# print(int(b))
# int/float --> str
print(str(a))
# bool --> int / float / str
flag = True
print(int(flag)) # 1
print(float(flag)) # 1.0
print(str(flag)) # "True"
# int/float/str --> bool: 變數的值是0,''(空字串),轉換結果為False,其餘為True
a = 2
print(bool(a)) # True
a = 0
print(bool(a)) # False
a = -1
print(bool(a)) # True
a = ''
print(bool(a)) # False
a = ' '
print(bool(a)) # True