自用總結。
零散知識
1.Python的計算方法:運算符、函數、方法
1) 方法與函數的區別:
方法與特定類型的對象有關,是屬于某個對象的函數,對象始終是該方法的第一個參數。e.g. islower()方法是檢查字符串中字符是否為小寫形式的方法:"hello".islower()、"one fish,two fish".count('fish')
函數在括號里輸入參數。
2) 運算符:
算術運算符: **冪 %取模 //向下取整
比較運算符
邏輯運算符:and or not
成員運算符: in、not in
恒等運算符:is、is not
x is None # 檢查x是否為None
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a == b) # True
print(a is b) # True
print(a == c) # True
print(a is c) # False
2.賦值與一些函數
x,y,z = 1,2,3
type(x)
len(x)
int(x)
float(x)
str(x)
3.print與input
name = input('please enter your name:')
print('hello',name)
print('hello,\nworld')
# 不能換行
print('''hello,
world''')
# 一定要換行
print('''hello,\n
world''')
print(r'''hello,\n
world''')
4.一些規則如果使用空格縮進,就一直用空格,不要用制表符
用4個空格縮進
在類之間空兩行(?)
字典、列表、元組以及參數列表中,在 ,后一個空格
字典的:后也要添加一個空格
在賦值運算符合比較運算符周圍要有空格(參數列表中除外),但是括號里不加空格。例如:a = f(1,2) + g(3,4)
5.變量名
普通字母、下劃線、數字。
不能有空格,不能以數字開頭,不能使用保留字或內置標識符(會報錯)
全部使用小寫字母并用下劃線分隔
6. PEP8 編碼規范
7.string字符串
用單雙引號均可
"hello, I'm xx."
'she said: "I am fine."'
'I\'m fine.'
# 單雙引號
'hello' + 'world' # helloworld 沒空格
'hello' * 2 # hellohellow 每空格
數據結構
1.list列表:可變、有序與字符串最相似,都支持len、索引、切片、成員運算符。但列表可以改,字符串不能改
Month = ['JAN', 'FEB'] 中括號
切片:[6:9] 取678
2.tuple元組:不可變、有序Month = ('JAN', 'FEB') 小括號;括號可省略:dimensions = 52, 40, 100
解包:length, width, height = dimensions
3.set集合:可變、無序,只包含唯一元素a = {1, 2, 3} 大括號
number = [1,2,6,3,1,1]
unique_nums = set(number)unique_nums.add(10) : 不是append,會把10放在任意位置
4.dictionary字典 :可變,無序,存儲元素對(鍵和值)鍵是不可變的,故list不能當鍵
student['Amy'] 數據結構的索引都是中括號
可以直接添加新鍵student['John'] = 12
檢查鍵是否在字典中:in、get 。如果預計查詢會失敗,最好用get。
print( 'Amy'in student)
print(student.get('Amy')) # 不存在輸出None
print(student.get('Amy'),'not') # 不存在輸出not復合字典:student['Amy']['age']