for循環
1、什么是for循環
循環就是重復做某件事,for循環是python提供第二種循環機制
2、為何要有for循環
理論上for循環能做的事情,while循環都可以做
之所以要有for循環,是因為for循環在循環取值(遍歷取值)比while循環更簡潔
3、如何用for循環
for循環語法如下:
1 for 變量名 in 可迭代對象: # 此時只需知道可迭代對象可以是字符串\列表\字典,我們之后會專門講解可迭代對象 2 代碼一 3 代碼二 4 ... 5 6 #例1 7 for item in ['a','b','c']: 8 print(item) 9 # 運行結果 10 a 11 b 12 c 13 14 # 參照例1來介紹for循環的運行步驟 15 # 步驟1:從列表['a','b','c']中讀出第一個值賦值給item(item=‘a’),然后執行循環體代碼 16 # 步驟2:從列表['a','b','c']中讀出第二個值賦值給item(item=‘b’),然后執行循環體代碼 17 # 步驟3: 重復以上過程直到列表中的值讀盡
案例一:打印數字0-6
1 # 簡單版:for循環的實現方式 2 for count in range(6): # range(6)會產生從0-5這6個數 3 print(count) 4 5 # 復雜版:while循環的實現方式 6 count = 0 7 while count < 6: 8 print(count) 9 count += 1
案例二:遍歷字典
1 # 簡單版:for循環的實現方式 2 for k in {'name':'jason','age':18,'gender':'male'}: # for 循環默認取的是字典的key賦值給變量名k 3 print(k) 4 5 # 復雜版:while循環確實可以遍歷字典,后續將會迭代器部分詳細介紹
案例三:for循環嵌套
1 #請用for循環嵌套的方式打印如下圖形: 2 ***** 3 ***** 4 ***** 5 6 for i in range(3): 7 for j in range(5): 8 print("*",end='') 9 print() # print()表示換行
案例四:列表循環取值
#簡單版:
1 l = ['alex_dsb', 'lxx_dsb', 'egon_nb'] 2 for x in l: # x='lxx_dsb' 3 print(x)
1 #復雜版:(while) 2 ['alex_dsb', 'lxx_dsb', 'egon_nb'] 3 i=0 4 while i < 3: 5 print(l[i]) 6 i+=1
二:總結for循環與while循環的異同
1、相同之處:都是循環,for循環可以干的事,while循環也可以干
2、不同之處:
while循環稱之為條件循環,循環次數取決於條件何時變為假
for循環稱之為"取值循環",循環次數取決in后包含的值的個數
案例五:for循環控制循環次數:range()
1 for i in range(30): 2 print('===>')
注意:for+else和for+break與continue也可以用於for循環,使用語法同while循環
1 username='egon' 2 password='123' 3 for i in range(3): 4 inp_name = input('請輸入您的賬號:') 5 inp_pwd = input('請輸入您的密碼:') 6 7 if inp_name == username and inp_pwd == password: 8 print('登錄成功') 9 break 10 else: 11 print('輸錯賬號密碼次數過多')
for+continue:
1 for i in range(6): # 0 1 2 3 4 5 2 if i == 4: 3 continue 4 print(i)
for循環嵌套:外層循環循環一次,內層循環需要完整的循環完畢
1 for i in range(3): 2 print('外層循環-->', i) 3 for j in range(5): 4 print('內層-->', j)
補充:終止for循環只有break一種方案
1 print('hello %s' % 'egon') 2 #1、print之逗號的使用 3 print('hello','world','egon') 4 #2、換行符 5 print('hello\n') 6 print('world') 7 #3、print值end參數的使用 8 print('hello\n',end='') 9 print('word') 10 print('hello',end='*') 11 print('world',end='*')
一.數字類型int型
一)定義:
1 # 1、定義:
2 # 1.1 整型int的定義
3 age=10 # 本質age = int(10)
4
5 # 1.2 浮點型float的定義
6 salary=3000.3 # 本質salary=float(3000.3)
7
8 # 注意:名字+括號的意思就是調用某個功能,比如
9 # print(...)調用打印功能
10 # int(...)調用創建整型數據的功能
11 # float(...)調用創建浮點型數據的功能
二)類型轉換
1 # 1、數據類型轉換
2 # 1.1 int可以將由純整數構成的字符串直接轉換成整型,若包含其他任意非整數符號,則會報錯
3 >>> s = '123'
4 >>> res = int(s) 5 >>> res,type(res) 6 (123, <class 'int'>) 7
8 >>> int('12.3') # 錯誤演示:字符串內包含了非整數符號.
9 Traceback (most recent call last): 10 File "<stdin>", line 1, in <module>
11 ValueError: invalid literal for int() with base 10: '12.3'
12
13 # 1.2 float同樣可以用來做數據類型的轉換
14 >>> s = '12.3'
15 >>> res=float(s) 16 >>> res,type(res) 17 (12.3, <class 'float'>)
三)使用
數字類型主要就是用來做數學運算與比較運算,因為此數字類型除了與運算符結合使用之外,並無需要掌握的內置方法
二.字符串類型
一)定義:
1 # 定義:在單引號\雙引號\三引號內包含一串字符
2 name1 = 'jason' # 本質:name = str('任意形式內容')
3 name2 = "lili" # 本質:name = str("任意形式內容")
4 name3 = """ricky""" # 本質:name = str("""任意形式內容""")
二)類型轉換
1 # 數據類型轉換:str()可以將任意數據類型轉換成字符串類型,例如
2 >>> type(str([1,2,3])) # list->str
3 <class 'str'>
4 >>> type(str({"name":"jason","age":18})) # dict->str
5 <class 'str'>
6 >>> type(str((1,2,3))) # tuple->str
7 <class 'str'>
8 >>> type(str({1,2,3,4})) # set->str
9 <class 'str'>
三)使用
1)優先掌握的操作
1 >>> str1 = 'hello python!'
2
3
4 # 1.按索引取值(正向取,反向取):
5 # 1.1 正向取(從左往右)
6 >>> str1[6] 7 p 8 # 1.2 反向取(負號表示從右往左)
9 >>> str1[-4] 10 h 11 # 1.3 對於str來說,只能按照索引取值,不能改
12 >>> str1[0]='H' # 報錯TypeError
13
14
15 # 2.切片(顧頭不顧尾,步長)
16 # 2.1 顧頭不顧尾:取出索引為0到8的所有字符
17 >>> str1[0:9] 18 hello pyt 19 # 2.2 步長:0:9:2,第三個參數2代表步長,會從0開始,每次累加一個2即可,所以會取出索引0、2、4、6、8的字符
20 >>> str1[0:9:2] 21 hlopt 22 # 2.3 反向切片
23 >>> str1[::-1] # -1表示從右往左依次取值
24 !nohtyp olleh 25
26 # 3.長度len
27 # 3.1 獲取字符串的長度,即字符的個數,但凡存在於引號內的都算作字符)
28 >>> len(str1) # 空格也算字符
29 13
30
31 # 4.成員運算 in 和 not in
32 # 4.1 int:判斷hello 是否在 str1里面
33 >>> 'hello' in str1 34 True 35 # 4.2 not in:判斷tony 是否不在 str1里面
36 >>> 'tony' not in str1 37 True 38
39 # 5.strip移除字符串首尾指定的字符(默認移除空格)
40 # 5.1 括號內不指定字符,默認移除首尾空格
41 >>> str1 = ' life is short! '
42 >>> str1.strip() 43 life is short! 44
45 # 5.2 括號內指定字符,移除首尾指定的字符
46 >>> str2 = '**tony**'
47 >>> str2.strip('*') 48 tony 49
50 # 6.切分split
51 # 6.1 括號內不指定字符,默認以空格作為切分符號
52 >>> str3='hello world'
53 >>> str3.split() 54 ['hello', 'world'] 55 # 6.2 括號內指定分隔字符,則按照括號內指定的字符切割字符串
56 >>> str4 = '127.0.0.1'
57 >>> str4.split('.') 58 ['127', '0', '0', '1'] # 注意:split切割得到的結果是列表數據類型
59
60
61 # 7.循環
62 >>> str5 = '今天你好嗎?'
63 >>> for line in str5: # 依次取出字符串中每一個字符
64 ... print(line) 65 ... 66 今 67 天 68 你 69 好 70 嗎 71 ?
2)需要掌握的操作
1.strip,lstrip,rstrip
1 >>> str1 = '**tony***'
2
3 >>> str1.strip('*') # 移除左右兩邊的指定字符
4 'tony'
5 >>> str1.lstrip('*') # 只移除左邊的指定字符
6 tony***
7 >>> str1.rstrip('*') # 只移除右邊的指定字符
8 **tony
2.lower(),upper()
1 >>> str2 = 'My nAme is tonY!'
2
3 >>> str2.lower() # 將英文字符串全部變小寫
4 my name is tony! 5 >>> str2.upper() # 將英文字符串全部變大寫
6 MY NAME IS TONY!
3.starts with,ends with
1 >>> str3 = 'tony jam'
2
3 # startswith()判斷字符串是否以括號內指定的字符開頭,結果為布爾值True或False
4 >>> str3.startswith('t') 5 True 6 >>> str3.startswith('j') 7 False 8 # endswith()判斷字符串是否以括號內指定的字符結尾,結果為布爾值True或False
9 >>> str3.endswith('jam') 10 True 11 >>> str3.endswith('tony') 12 False
4.格式化輸出之format
1 # format括號內在傳參數時完全可以打亂順序,但仍然能指名道姓地為指定的參數傳值,name=‘tony’就是傳給{name}
2 >>> str4 = 'my name is {name}, my age is {age}!'.format(age=18,name='tony') 3 >>> str4 4 'my name is tony, my age is 18!'
5
6 >>> str4 = 'my name is {name}{name}{name}, my age is {name}!'.format(name='tony', age=18) 7 >>> str4 8 'my name is tonytonytony, my age is tony!'
format的其他使用方式(了解)
1 # 類似於%s的用法,傳入的值會按照位置與{}一一對應
2 >>> str4 = 'my name is {}, my age is {}!'.format('tony', 18) 3 >>> str4 4 my name is tony, my age is 18!
1 # 把format傳入的多個值當作一個列表,然后用{索引}取值
2 >>> str4 = 'my name is {0}, my age is {1}!'.format('tony', 18) 3 >>> str4 4 my name is tony, my age is 18! 5
6 >>> str4 = 'my name is {1}, my age is {0}!'.format('tony', 18) 7 >>> str4 8 my name is 18, my age is tony! 9
10 >>> str4 = 'my name is {1}, my age is {1}!'.format('tony', 18) 11 >>> str4 12 my name is 18, my age is 18!
5.split,rsplit
1 # split會按照從左到右的順序對字符串進行切分,可以指定切割次數
2 >>> str5='C:/a/b/c/d.txt'
3 >>> str5.split('/',1) 4 ['C:', 'a/b/c/d.txt'] 5
6 # rsplit剛好與split相反,從右往左切割,可以指定切割次數
7 >>> str5='a|b|c'
8 >>> str5.rsplit('|',1) 9 ['a|b', 'c']
6.join
1 #
2 >>> '%'.join('hello') # 從字符串'hello'中取出多個字符串,然后按照%作為分隔符號進行拼接
3 'h%e%l%l%o'
4 >>> '|'.join(['tony','18','read']) # 從列表中取出多個字符串,然后按照*作為分隔符號進行拼接
5 'tony|18|read'
7.replace(替換)
1 # 用新的字符替換字符串中舊的字符
2 >>> str7 = 'my name is tony, my age is 18!' # 將tony的年齡由18歲改成73歲
3 >>> str7 = str7.replace('18', '73') # 語法:replace('舊內容', '新內容')
4 >>> str7 5 my name is tony, my age is 73! 6
7 # 可以指定修改的個數
8 >>> str7 = 'my name is tony, my age is 18!'
9 >>> str7 = str7.replace('my', 'MY',1) # 只把一個my改為MY
10 >>> str7 11 'MY name is tony, my age is 18!'
8.isdigit
1 # 判斷字符串是否是純數字組成,返回結果為True或False
2 >>> str8 = '5201314'
3 >>> str8.isdigit() 4 True 5
6 >>> str8 = '123g123'
7 >>> str8.isdigit() 8 False
3)了解操作
1 # 1.find,rfind,index,rindex,count
2 # 1.1 find:從指定范圍內查找子字符串的起始索引,找得到則返回數字1,找不到則返回-1
3 >>> msg='tony say hello'
4 >>> msg.find('o',1,3) # 在索引為1和2(顧頭不顧尾)的字符中查找字符o的索引
5 1
6 # 1.2 index:同find,但在找不到時會報錯
7 >>> msg.index('e',2,4) # 報錯ValueError
8 # 1.3 rfind與rindex:略
9 # 1.4 count:統計字符串在大字符串中出現的次數
10 >>> msg = "hello everyone"
11 >>> msg.count('e') # 統計字符串e出現的次數
12 4
13 >>> msg.count('e',1,6) # 字符串e在索引1~5范圍內出現的次數
14 1
15
16 # 2.center,ljust,rjust,zfill
17 >>> name='tony'
18 >>> name.center(30,'-') # 總寬度為30,字符串居中顯示,不夠用-填充
19 -------------tony-------------
20 >>> name.ljust(30,'*') # 總寬度為30,字符串左對齊顯示,不夠用*填充
21 tony**************************
22 >>> name.rjust(30,'*') # 總寬度為30,字符串右對齊顯示,不夠用*填充
23 **************************tony 24 >>> name.zfill(50) # 總寬度為50,字符串右對齊顯示,不夠用0填充
25 0000000000000000000000000000000000000000000000tony 26
27 # 3.expandtabs
28 >>> name = 'tony\thello' # \t表示制表符(tab鍵)
29 >>> name 30 tony hello 31 >>> name.expandtabs(1) # 修改\t制表符代表的空格數
32 tony hello 33
34 # 4.captalize,swapcase,title
35 # 4.1 captalize:首字母大寫
36 >>> message = 'hello everyone nice to meet you!'
37 >>> message.capitalize() 38 Hello everyone nice to meet you! 39 # 4.2 swapcase:大小寫翻轉
40 >>> message1 = 'Hi girl, I want make friends with you!'
41 >>> message1.swapcase() 42 hI GIRL, i WANT MAKE FRIENDS WITH YOU! 43 #4.3 title:每個單詞的首字母大寫
44 >>> msg = 'dear my friend i miss you very much'
45 >>> msg.title() 46 Dear My Friend I Miss You Very Much 47
48 # 5.is數字系列
49 #在python3中
50 num1 = b'4' #bytes
51 num2 = u'4' #unicode,python3中無需加u就是unicode
52 num3 = '四' #中文數字
53 num4 = 'Ⅳ' #羅馬數字
54
55 #isdigt:bytes,unicode
56 >>> num1.isdigit() 57 True 58 >>> num2.isdigit() 59 True 60 >>> num3.isdigit() 61 False 62 >>> num4.isdigit() 63 False 64
65 #isdecimal:uncicode(bytes類型無isdecimal方法)
66 >>> num2.isdecimal() 67 True 68 >>> num3.isdecimal() 69 False 70 >>> num4.isdecimal() 71 False 72
73 #isnumberic:unicode,中文數字,羅馬數字(bytes類型無isnumberic方法)
74 >>> num2.isnumeric() 75 True 76 >>> num3.isnumeric() 77 True 78 >>> num4.isnumeric() 79 True 80
81 # 三者不能判斷浮點數
82 >>> num5 = '4.3'
83 >>> num5.isdigit() 84 False 85 >>> num5.isdecimal() 86 False 87 >>> num5.isnumeric() 88 False 89
90 '''
91 總結: 92 最常用的是isdigit,可以判斷bytes和unicode類型,這也是最常見的數字應用場景 93 如果要判斷中文數字或羅馬數字,則需要用到isnumeric。 94 '''
95
96 # 6.is其他
97 >>> name = 'tony123'
98 >>> name.isalnum() #字符串中既可以包含數字也可以包含字母
99 True 100 >>> name.isalpha() #字符串中只包含字母
101 False 102 >>> name.isidentifier() 103 True 104 >>> name.islower() # 字符串是否是純小寫
105 True 106 >>> name.isupper() # 字符串是否是純大寫
107 False 108 >>> name.isspace() # 字符串是否全是空格
109 False 110 >>> name.istitle() # 字符串中的單詞首字母是否都是大寫
111 False
三.列表
一)定義
1 # 定義:在[]內,用逗號分隔開多個任意數據類型的值
2 l1 = [1,'a',[1,2]] # 本質:l1 = list([1,'a',[1,2]])
二)類型轉換
1 # 但凡能被for循環遍歷的數據類型都可以傳給list()轉換成列表類型,list()會跟for循環一樣遍歷出數據類型中包含的每一個元素然后放到列表中
2 >>> list('wdad') # 結果:['w', 'd', 'a', 'd']
3 >>> list([1,2,3]) # 結果:[1, 2, 3]
4 >>> list({"name":"jason","age":18}) #結果:['name', 'age']
5 >>> list((1,2,3)) # 結果:[1, 2, 3]
6 >>> list({1,2,3,4}) # 結果:[1, 2, 3, 4]
三)使用
1)優先掌握的操作
1 # 1.按索引存取值(正向存取+反向存取):即可存也可以取
2 # 1.1 正向取(從左往右)
3 >>> my_friends=['tony','jason','tom',4,5] 4 >>> my_friends[0] 5 tony 6 # 1.2 反向取(負號表示從右往左)
7 >>> my_friends[-1] 8 5
9 # 1.3 對於list來說,既可以按照索引取值,又可以按照索引修改指定位置的值,但如果索引不存在則報錯
10 >>> my_friends = ['tony','jack','jason',4,5] 11 >>> my_friends[1] = 'martthow'
12 >>> my_friends ['tony', 'martthow', 'jason', 4, 5] 13
14 # 2.切片(顧頭不顧尾,步長)
15 # 2.1 顧頭不顧尾:取出索引為0到3的元素
16 >>> my_friends[0:4] ['tony', 'jason', 'tom', 4] 17 # 2.2 步長:0:4:2,第三個參數2代表步長,會從0開始,每次累加一個2即可,所以會取出索引0、2的元素
18 >>> my_friends[0:4:2] ['tony', 'tom'] 19 # 3.長度
20 >>> len(my_friends) 21 5
22 # 4.成員運算in和not in
23 >>> 'tony' in my_friends 24 True 25 >>> 'xxx' not in my_friends 26 True 27 # 5.添加
28 # 5.1 append()列表尾部追加元素
29 >>> l1 = ['a','b','c'] 30 >>> l1.append('d') 31 >>> l1 ['a', 'b', 'c', 'd'] 32 # 5.2 extend()一次性在列表尾部添加多個元素
33 >>> l1.extend(['a','b','c']) 34 >>> l1 ['a', 'b', 'c', 'd', 'a', 'b', 'c'] 35 # 5.3 insert()在指定位置插入元素
36 >>> l1.insert(0,"first") 37 # 0表示按索引位置插值
38 >>> l1 ['first', 'a', 'b', 'c', 'd', 'a', 'b', 'c'] 39 # 6.刪除
40 # 6.1 del
41 >>> l = [11,22,33,44] 42 >>> del l[2] 43 # 刪除索引為2的元素
44 >>> l [11,22,44] 45 # 6.2 pop()默認刪除列表最后一個元素,並將刪除的值返回,括號內可以通過加索引值來指定刪除元素
46 >>> l = [11,22,33,22,44] 47 >>> res=l.pop() >>> res 44
48 >>> res=l.pop(1) 49 >>> res 22
50 # 6.3 remove()括號內指名道姓表示要刪除哪個元素,沒有返回值
51 >>> l = [11,22,33,22,44] 52 >>> res=l.remove(22) 53 # 從左往右查找第一個括號內需要刪除的元素
54 >>> print(res) None 55 # 7.reverse()顛倒列表內元素順序
56 >>> l = [11,22,33,44] 57 >>> l.reverse() 58 >>> l [44,33,22,11] 59 # 8.sort()給列表內所有元素排序
60 # 8.1 排序時列表元素之間必須是相同數據類型,不可混搭,否則報錯
61 >>> l = [11,22,3,42,7,55] >>> l.sort() 62 >>> l [3, 7, 11, 22, 42, 55] 63 # 默認從小到大排序
64 >>> l = [11,22,3,42,7,55] 65 >>> l.sort(reverse=True) 66 # reverse用來指定是否跌倒排序,默認為False
67 >>> l [55, 42, 22, 11, 7, 3] 68 # 8.2 了解知識:
69 # 我們常用的數字類型直接比較大小,但其實,字符串、列表等都可以比較大小,原理相同:都是依次比較對應位置的元素的大小,如果分出大小,則無需比較下一個元素,比如
70 >>> l1=[1,2,3] 71 >>> l2=[2,] 72 >>> l2 > l1 True 73 # 字符之間的大小取決於它們在ASCII表中的先后順序,越往后越大
74 >>> s1='abc'
75 >>> s2='az'
76 >>> s2 > s1 77 # s1與s2的第一個字符沒有分出勝負,但第二個字符'z'>'b',所以s2>s1成立 True # 所以我們也可以對下面這個列表排序
78 >>> l = ['A','z','adjk','hello','hea'] 79 >>> l.sort() 80 >>> l ['A', 'adjk', 'hea', 'hello','z'] 81 # 9.循環 # 循環遍歷my_friends列表里面的值
82 for line in my_friends: 83 print(line) 84 'tony' 'jack' 'jason' 4 5
2)了解操作
1 >>> l=[1,2,3,4,5,6] 2 >>> l[0:3:1] 3 [1, 2, 3] # 正向步長
4 >>> l[2::-1] 5 [3, 2, 1] # 反向步長
6
7 # 通過索引取值實現列表翻轉
8 >>> l[::-1] 9 [6, 5, 4, 3, 2, 1]
五.元組
一)作用
元組與列表類似,也是可以存多個任意類型的元素,不同之處在於元祖的元素不能修改,即元組相當於不可變的列表,用於記錄多個固定不允許修改的值,單純用於取
二)定義
1 # 在()內用逗號分隔開多個任意類型的值
2 >>> countries = ("中國","美國","英國") 3 # 本質:countries = tuple("中國","美國","英國")
4 # 強調:如果元組內只有一個值,則必須加一個逗號,否則()就只是包含的意思而非定義元組
5 >>> countries = ("中國",) # 本質:countries = tuple("中國")
三)轉換類型
1 # 但凡能被for循環的遍歷的數據類型都可以傳給tuple()轉換成元組類型
2 >>> tuple('wdad') # 結果:('w', 'd', 'a', 'd')
3 >>> tuple([1,2,3]) # 結果:(1, 2, 3)
4 >>> tuple({"name":"jason","age":18}) # 結果:('name', 'age')
5 >>> tuple((1,2,3)) # 結果:(1, 2, 3)
6 >>> tuple({1,2,3,4}) # 結果:(1, 2, 3, 4)
7 # tuple()會跟for循環一樣遍歷出數據類型中包含的每一個元素然后放到元組中
四)使用
1 >>> tuple1 = (1, 'hhaha', 15000.00, 11, 22, 33) 2 # 1、按索引取值(正向取+反向取):只能取,不能改否則報錯!
3 >>> tuple1[0] 4 1
5 >>> tuple1[-2] 6 22
7 >>> tuple1[0] = 'hehe' # 報錯:TypeError:
8
9 # 2、切片(顧頭不顧尾,步長)
10 >>> tuple1[0:6:2] 11 (1, 15000.0, 22) 12
13 # 3、長度
14 >>> len(tuple1) 15 6
16
17 # 4、成員運算 in 和 not in
18 >>> 'hhaha' in tuple1 19 True 20 >>> 'hhaha' not in tuple1 21 False 22
23 # 5、循環
24 >>> for line in tuple1: 25 ... print(line) 26 1
27 hhaha 28 15000.0
29 11
30 22
31 33
六.字典
一)定義
二)類型轉換
三)使用
七.集合
一)作用:集合 list tuple dict一樣都可以存放多個值,但實際和主要用於:去重 關系運算
二)定義:
三)類型轉換
四)使用
1)關系運算
