學習Python,一是由於暑假學的c++頭疼,據說Python簡單,那我就試試吧,二是由於Python形勢一片大好,算是附和潮流吧!python
1、初識Pythonc++
一、第一個Python代碼git
1 print("Hello World")
依然是熟悉的Hello World, 對於只學過c和c++的我來講,着實有點奇怪,怎麼main()沒了(實際上是有的),頭文件也沒了,甚至連一句語句的末尾標識逗號也不見蹤跡。api
二、概覽app
用下面一段猜大小的代碼碼來解釋一下python與c(c++)的區別dom
c:學習
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<time.h> 4 5 int main(void) 6 { 7 int try_num, true_num, x, count; 8 9 while(1) 10 { 11 printf("請選擇: 1.猜大小 2.退出: "); 12 scanf("%d", &x); 13 if(x == 2) 14 break; 15 srand(time(0)); 15 true_num = rand() % 100 + 1; 16 printf("請輸入你猜的數字(1-100): "); 17 scanf("%d", &try_num); 18 count = 1; 19 while(try_num != true_num) 20 { 21 if(try_num >= 1 && try_num <= 100) 22 { 23 if(try_num > true_num) 24 printf("你猜大了!\n"); 25 else 26 printf("你猜小了!\n"); 27 } 28 else 29 printf("你輸入的數字有誤!\n"); 30 printf("請再次輸入你猜的數字: "); 31 scanf("%d", &try_num); 32 count++; 33 } 34 printf("你終於猜對了, 共用了%d次.\n", count); 35 } 36 37 return 0; 38 }
Python:spa
1 import random 2 3 4 while True: 5 x = int(input("請選擇: 1.猜大小 2.退出: ")) 6 if x == 2: 7 break 8 true_num = random.randint(1, 100) 9 try_num = int(input("請輸入你猜的數字(1-100): ")) 10 count = 1 11 while try_num != true_num: 13 if try_num in range(1, 101): 14 if try_num > true_num: 15 print("你猜大了!") 16 else: 17 print("你猜小了!") 18 else: 19 print("你輸入的數字有誤!") 20 try_num = int(input("請再次輸入你猜的數字: ")) 21 count += 1 22 print("你終於猜對了, 共用了%d次" % count)
能清楚的看出,用Python寫出的代碼較c簡潔美觀,沒有冗餘,在語法上的幾點區別總結以下:c++11
二者也具備高級語言的相似特色:orm
2、基本數據類型
與c不一樣,Python的面向對象特徵更加明顯,連int,float等也有本身的方法;
與c++相比,Python的list,tuple,dict 等相較與STL的容器更容易使用,內置的方法也較豐富
一、int, float, complex
int, float,complex方法
對於complex a, 能夠經過a.real和a.imag使用其實部和虛部
二、bool: True, False
例如, 能夠
1 a = True 2 while a: 3 # ... 4 if ...: 5 a = False
三、str: 經過'', "" 或 str()構建
str方法
a.對str中的方法的總結:
b.幾個方法詳解:
1 # 經過位置 2 string1 = "{0} is the most {1} teacher of life" 3 str1 = string1.format("Suffering", "powerful") 4 # str1 = "Suffering is the most powerful teacher of life" 5 string2 = "{0}, {1}, {0}" 6 str2 = string2.format("Edward", "Tang"} 7 # str2 = "Edward, Tang, Edward" 8 9 # 經過關鍵詞 10 string = "{name} is {age}" 11 str = string.format(name="Edward", age=19) 12 # str = "Edward is 19" 13 14 # 填充和對齊 15 # ^、<、>分別是居中、左對齊、右對齊,後面帶寬度 16 # :號後面帶填充的字符,只能是一個字符,不指定的話默認是用空格填充 17 string1 = "{: >6}" 18 str1 = string1.format("Ed") 19 # str1 = " Ed" 20 string2 = "{:*<6}" 21 str2 = string2.format("Ed") 22 # str2 = "Ed****" 23 24 # 控制精度 25 string = 「{:.2f}」 26 str1 = string.format(3.1415926) 27 # str1 = "3.14" 28 29 # 金額分隔符 30 string = "{:,}" 31 str = string.format(1234567) 32 # str = "1,234,567"
1 # s.maketrans('s1', 's2') s1 和 s2 的長度必須一致,生成一個轉換表 2 # s.translate(table) 對字符串s按照table裏的字符映射關係替換 3 s = "I was a handsome boy" 4 table = s.maketrans("abcde", "12345") 5 str = s.translate(table) 6 # str = "I w1s 1 h1n4som5 2oy"
1 # join用於用指定str鏈接參數的str序列 2 lst = ['a', 'b', 'c', 'd'] 3 s = '-'.join(lst) 4 # s = "a-b-c-d" 5 6 def accum(s): 7 return '-'.join(c.upper() + c.lower() * i for i, c in enumerate(s)) 8 # s = "abcd",返回 「A-Bb-Ccc-Dddd」 9 10 # split用於用指定參數拆分str 11 s = "a-b-c-d" 12 lst = s.split('-') 13 # lst = ['a', 'b', 'c', 'd']
c.索引和切片:
Python中的索引和C相似,可是能夠從右邊開始:
1 word = "python" 2 # word[0] = 'p' 3 # word[5] = 'n' 4 # word[-1] = 'n', 表示最後一個, -0和0同樣
除了索引, 還支持切片:
1 word = "python" 2 # word[0: 2] = 'py' 3 # word[2: 5] = 'tho' 4 # word[: 2] = 'py', 等同於[0: 2] 5 # word[3:] = 'hon', 等同於[3: len(word)] 6 # word[::-1] = "nohtyp",反轉字符串
切片和c++中的迭代器相似,都是爲單閉合區間;
切記str是const的, 不能夠經過賦值等改變它們
四、list:經過[]或list()構建
1 def append(self, p_object): 2 pass 3 # 添加元素p_object到list末尾,p_object能夠是任何類型 4 5 def clear(self): 6 pass 7 # 清空list中的元素 8 9 def copy(self): 10 pass 11 # 返回一個list的淺拷貝 12 13 def count(self, value): 14 pass 15 # 返回list中的value的個數 16 17 def extend(self, iterable) 18 pass 19 # 添加整個iterable到list末尾,擴展list 20 21 def index(self, value, start=None, stop=None): 22 pass 23 # 返回子序列[start, stop)中value第一次出現的下標,未找到報錯 24 25 def insert(self, index, p_object): 26 pass 27 # 插入一個p_object到下標爲index的元素以前 28 29 def pop(self, index=None): 30 pass 31 # 彈出index位置的元素並返回此元素, list爲空或index超出範圍會報錯 32 33 def remove(self, value): 34 pass 35 # 清除list中第一個值爲value的元素,不返回此值 36 37 def reverse(self): 38 pass 39 # 反轉整個list 40 41 def sort(self, key=None, reverse=False): 42 pass 43 # 排序list,key能夠爲lambda或cmp,reverse爲True須要反轉
a.對list中方法的總結:
b.幾個方法詳解:
1 lst = [1, 5, 4, 3, 8] 2 lst.append(3) 3 # lst = [1, 5, 4, 3, 8, 3] 4 lst.append([1, 2, 3]) 5 # lst = [1, 5, 4, 3, 8, 3, [1, 2, 3]],始終把參數當作一個元素 6 lst.extend([1, 2, 3]) 7 #[1, 5, 4, 3, 8, 3, [1, 2, 3], 1, 2, 3],合併爲一個list
c.索引和切片:
與str基本一致,可是因爲list可變,還存在一個del語言:
1 lst = [3, 4, 5, 6, 7] 2 del lst[0] 3 # lst = [4, 5, 6, 7] 4 del lst[1:3] 5 # lst = [4, 7] 6 del lst[:] 7 # lst = []
5.tuple:經過()或tuple()構建(括號能夠省略), 只包含一個元素時,在元素後面添加逗號
def count(self, value): pass # 返回tuple中value的個數 def index(self, value, start=None, stop=None): pass # 返回子序列[start, stop)中第一個值爲value的下標
tuple和list的區別在於其不能改變,全部不少方法沒有
tuple也有索引和切片,再也不贅述
要想對tuple進行強制修改,能夠經過list()構造
6.dict:經過{}或dict()構建
1 def clear(self): 2 pass 3 # 清空dict中的元素 4 5 def copy(self): 6 pass 7 # 返回dict的一個拷貝 8 9 def fromkeys(*args, **kwargs): 10 pass 11 # 返回一個dict,全部的key都對應同一個value(默認爲None) 12 13 def get(self, k, d=None): 14 pass 15 # 返回key爲k時對應的value,若是不存在,返回d 16 17 def setdefault(self, k, d=None): 18 pass 19 # 返回key爲k時對應的value,若是不存在,添加一個k: d 20 21 def items(self): 22 pass 23 # 返回dict中全部key, value構成的dict_items() 24 25 def keys(self): 26 pass 27 # 返回dict中全部key構成的dict_keys() 28 29 def values(self): 30 pass 31 # 返回dict中全部value構成的dict_values() 32 33 def pop(self, k, d=None): 34 pass 35 # 彈出dict中k所對應的value,沒找到返回d 36 37 def popitem(self): 38 pass 39 # 隨機彈出dict中一個(key, value),dict爲空時出錯 40 41 def update(self, E=None, **F): 42 pass 43 # 用另外一個dict F 來更新原dict, 返回None
a.對dict中方法的總結:
b.幾個方法詳解:
1 dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} 2 # key爲str的構建時也能夠寫成 dic = dict(k1 = 'v1', k2 = 'v2', k3 = 'v3) 3 k = dic.pop('k1') 4 # k = 'v1'且 dic = {'k2': 'v2', 'k3': 'v3'} 5 item = dic.popitems() 6 # item = (‘k2’, 'v2')或('k3', v3') 由於dic是無序的,且dic會隨之變化
1 dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} 2 s1 = get('k1') # s1 = dic['k1'] 3 s2 = get('k4', 'v4') # s2 = 'v4' 4 s1 = setdefault('k1') # s1 = dic['k1'] 5 s2 = setdefault('k4', 'v4') # dic['k4'] = 'v4'
1 dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} 2 for k in dic.keys(): 3 print(k) 4 for v in dic.values(): 5 print(v) 6 for k, v in dic.items(): 7 print(k, v) 8 # 分別輸出了dic中全部的key, value和鍵值對
1 # fromkeys第一個參數能夠是任意類型的序列, 2 # 第二個參數爲空默認value都爲None 3 dic = dict.fromkeys(('k1', 'k2', 'k3')) 4 # dic = {'k2': None, 'k1': None, 'k3': None} 5 dic = dict.fromkeys(('k1', 'k2', 'k3'), 520) 6 # dic = {'k2': 520, 'k3': 520, 'k1': 520} 7 8 # update將dic1更新, 返回None 9 dic1 = {'k1': 13, 'k2': 14, 'k3': 520} 10 dic2 = {'k4': 'Edward', 'k3': '250'} 11 dic = dic1.update(dic2) 12 # dic = None 13 # dic2 = {'k1': 13, 'k2': 14, 'k3': 250, 'k4': 'Edward'}
7.set:經過set()構建
1 def add(self, *args, **kwargs): 2 pass 3 # 向set中添加一個元素,返回None 4 5 def clear(self, *args, **kwargs): 6 pass 7 # 清空set中的元素 8 9 def copy(self, *args, **kwargs): 10 pass 11 # 返回一個set的淺拷貝 12 13 def difference(self, *args, **kwargs): 14 pass 15 # 返回一個set,其中不含參數集合中的元素,差集 16 17 def difference_update(self, *args, **kwargs): 18 pass 19 # 和difference()相比,set自身更新爲差集,返回None 20 21 def symmetric_difference(self, *args, **kwargs): 22 pass 23 # 返回集合之間的對稱差集 24 25 def symmetric_difference_update(self, *args, **kwargs): 26 pass 27 # 和symmetric_difference()相比,set自身更新爲對稱差集,返回None 28 29 def intersection(self, *args, **kwargs): 30 pass 31 # 返回set和參數集合的交集 32 33 def intersection_update(self, *args, **kwargs): 34 pass 35 # 和intersection()相比,set自身更新爲交集,返回None 36 37 def union(self, *args, **kwargs): 38 pass 39 # 返回set和參數集合的並集 40 41 def update(self, *args, **kwargs): 42 pass 43 # 和union()相比,set自身更新爲並集,返回None 44 45 def discard(self, *args, **kwargs): 46 pass 47 # 清除set中的參數元素,返回None, 若沒有不作任何事, 48 49 def isdisjoint(self, *args, **kwargs): 50 pass 51 # 返回集合之間是否交集爲空 52 53 def issubset(self, *args, **kwargs): 54 pass 55 # 返回是否set爲參數集合的子集 56 57 def issuperset(self, *args, **kwargs): 58 pass 59 # 返回是否set爲參數集合的父集 60 61 def pop(self, *args, **kwargs): 62 pass 63 # 彈出set中一個隨機的值並返回,set爲空會出錯 64 65 def remove(self, *args, **kwargs): 66 pass 67 # 清除set中的參數元素,返回None,沒有會出錯
a.對set中方法的總結:
b.集合的運算符:
a, b, c均爲集合 差集:c = a - b 等同於 c = a.difference(b) a -= b 等同於 a.difference_update(b) 對稱差集:c = a ^ b 等同於 c = a.symmetric_difference(b) a ^= b 等同於 a.symmetric_difference_update(b) 交集:c = a & b 等同於 c = a.intersection(b) a &= b 等同於 a.intersection_update(b) 並集:c = a | b 等同於 c = a.union(b) a |= b 等同於 a.update(b) 判斷子集: a <= b 等同於 a.issubset(b) 判斷父集: a >= b 等同於 a.issupperset(b)