這里面記錄一些python的一些基礎知識,數據類型和變量。幸而下雨,雨在街上潑,卻潑不進屋內。人靠在一塊玻璃窗旁,便會覺得幸福。這個家還是像個家的。
python的一些基礎使用
一、python中的數據類型和變量知識
print("%s is number %d!" % ('python', 34)) # 把內容寫到文件中 logfile = open('huhx.txt', 'a') print('Fatal error: invalid input', file=logfile) logfile.close() content = input("please input:") print(content)
python的注釋有兩種,一種是上述的使用#號,另外一種是文檔字符串的注釋。用在模塊、類或者函數的起始處,起到在線文檔的功能。與普通注釋不同,文檔字符串可以在運行時訪問,也可以用來自動生成文檔。
def foo(): "this is a doc string" return True
python中的一些運算符,這里列舉一些與java所不同的地方。
# **表示乘方, /表示傳統除法,//表示整除時的商, %表示余數 print(3 ** 2, 5 / 3, 5 // 3, 5 % 3, sep=" ") # 9 1.6666666666666667 1 2
python中的一些比較運算符號,其中<>和!=一樣表示不等於,但是推薦使用!=。
< <= > >= == != <>
python中提供的邏輯運算符號:and or not分別對應於java中&& || !。注意的是python支持3 < 4 < 5的這種寫法。
print(3 < 4 and 4 < 5, 3 < 4 < 5, sep=" ") # True True
python也支持增量賦值,但是不支持java中自增長++n什么。Python會將下述的 --n 解釋為-(-n) 從而得到 n , 同樣 ++n 的結果也是 n.
num = 45 num += 55 print(num, --num, ++num, sep=" ") # num++寫法會報錯,打印結果:100 100 100
以下的對象的布爾值為False
None, False, 所有的值為零的數, 0 (整型), (浮點型), 0L (長整型), 0.0+0.0j (復數), "" (空字符串), [] (空列表), () (空元組), {} (空字典)
二、python中的數字與字符串
Python 支持五種基本數字類型:int (有符號整數),long (長整數),bool (布爾值),float (浮點值)和complex (復數)。
python中的加號( + )用於字符串連接運算,與java不同的是星號( * )可以用於字符串重復。
name = "huhx" print(name * 2, name + "linux") # huhxhuhx huhxlinux
但是需要注意的是,如果字符串+一個數字的話,就會報錯。
print("huhx" + 1) # TypeError: must be str, not int
對於單個字符的編碼,Python提供了ord()函數獲取字符的整數表示,chr()函數把編碼轉換為對應的字符:
print(ord('中'), chr(25991)) # 20013 文
python中的decode與encode函數,下述的b'\xe4\xb8\xad\xe6\x96\x87'表示的是以字節為單位的bytes。
# b'\xe4\xb8\xad\xe6\x96\x87' 中文 print('中文'.encode('utf-8'), b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8'))
len()函數計算的是str的字符數,如果換成bytes,len()函數就計算字節數:
print(len('中文'), len('中文'.encode('utf-8'))) # 2 6
三、列表list與元組tuple的使用
- list是一種有序的集合,可以隨時添加和刪除其中的元素。
聲明創建一個列表,可以看到可以有不同的類型。
fruit = ['apple', 'orange', 45]
得到列表的長度:
print(len(fruit)) # 3
用索引來訪問list中每一個位置的元素:
print(fruit[0], fruit[1], fruit[2]) # apple orange 45
得到最后一個元素:
print(fruit[len(fruit) - 1], fruit[-1]) # 45 45
以下列舉一下關於list的一些操作:
# 追加元素到末尾 print(fruit.append('huhx')) # None # 元素插入到指定的位置 print(fruit.insert(1, 'linux')) # None # 刪除list末尾的元素 print(fruit.pop()) # huhx # 刪除指定位置的元素 print(fruit.pop(0)) # apple # 某個元素替換成別的元素 fruit[0] = 'pear'
- tuple和list非常類似,但是tuple一旦初始化就不能修改
classmate = ('huhx', 'linux', 'tomhu') print(classmate[1], classmate.index('linux')) # linux friend = 'huhx' if friend in classmate: print(classmate.index(friend)) # 0
對於tuple中的index方法,如果元素不在tuple中。那么會報錯。
print(classmate.index('hu'), 'huhx') # ValueError: tuple.index(x): x not in tuple
tuple一旦定義就不能變了,它也沒有append(),insert()這樣的方法。其他獲取元素的方法和list是一樣的,你可以正常地使用classmate[0],classmate[-1],但不能賦值成另外的元素。
當tuple只有一個元素的時候,定義需要注意一下。如下
t = (1) # 這里定義和t=1是一樣的。()被認為是小括號 print(t + 45) # 46 t = (1,) # 這是定義一個元素的正確寫法 print(t[0]) # 1
四、字典map與set的使用
map的創建有以下的幾種方式:
>>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> a == b == c == d == e True
訪問map中的值:需要注意的是python對於map、turple等的一些取值操作。如果沒有對應的key,就會報錯。
dataMap = {'name': 'huhx', 'password': '123456', 8: 8} # map的創建 # print(dataMap['username']) # KeyError: 'username' if 'name' in dataMap: print(dataMap['name']) # huhx print(dataMap.get('username', 'linux')) # linux
# map的遍歷,有以下兩種方式 for key in dataMap: print('key = %s, and value = %s' % (key, dataMap.get(key))) for key, item in dataMap.items(): print(key, item)
map的更新:涉及到添加元素或者修改元素
dataMap['name'] = 'liuling' # modify dataMap['age'] = 34 # add
map刪除字典元素或者刪除字典
del dataMap['name'] # 刪除key=name的元素 dataMap.clear() # 刪除dataMap中所有的元素 del dataMap # 刪除dataMap dataMap.pop('name') # 刪除並返回key=name的value值
五、int函數的使用
int函數能夠將字符串轉換成整數,也可以將浮點數轉換成整數。
print(int(12.2)) # 12 print(int('12.2')) # ValueError: invalid literal for int() with base 10: '12.2' print(int('34')) # 34
六、列表和字符串的遍歷
if __name__ == '__main__': aList = [1, 2, 'huhx', '4'] content = 'huhx' # 列表的遍歷 for item in aList: print(item) for index in range(len(aList)): print('%s (%d)' % (aList[index], index)) for index, value in enumerate(aList): print(index, value) # 字符串的遍歷 for string in content: print(string) # range函數的使用 for num in range(3): print(num)
七、python中一些內建函數的使用
complex(3, -45.4) # (3-45.4j) float('23.334') # 23.334 divmod(10, 4) # (2, 2) round(3.49999) # 3 round(3.49999, 1) # 3.5
int(), round(), math.floor()函數的區別:
函數 int()直接截去小數部分。(返回值為整數) 函數 floor()得到最接近原數但小於原數的整數。(返回值為浮點數) 函數 round()得到最接近原數的整數。(返回值為浮點數)
pow函數的使用:如果有第三個參數,那么就是結果取余操作。
pow(3, 2) # 9 pow(3, 2, 4) # 1
進制轉換函數:
hex(234) # 0xea oct(245) # 0o365
ASCII 轉換函數:
ord('a') # 97 chr(97) # a
編碼與解碼函數:
'中文'.encode('utf-8') # b'\xe4\xb8\xad\xe6\x96\x87' b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8') # 中文
友情鏈接