(1)函數的定義:可由字母,下劃線和數字組成,但不能以數字開頭,且不能與關鍵字相同 練習1:第一個函數 #注意定義函數之后只表示代碼封裝,需主動調用,函數定義必須寫在調用之前 def say_hello(): '''打招呼''' print('hello 1') print('hello 2')say_hello()
執(zhí)行結果:C:\python\0\venv\Scripts\python.exe C:/python/0/first_函數.pyhello 1hello 2Process finished with exit code 0 注:函數定義上方與其他代碼保留兩個空行,且將函數說明用引號寫在函數內部,在PyCharm中可用Ctrl+Q查看函數相關信息 (2)函數參數的使用:在函數名后面的括號內可填寫參數,參數之間使用逗號進行分離;調用函數時按照參數定義(形參)順序依次寫入傳遞的參數值(實參) 函數的返回值:在函數中使用return關鍵字可返回函數值;當調用函數時可使用變量來接收函數的返回結果 練習2:兩個數字的求和 def sum(number1,number2): '''兩個數字求和''' #調用函數,并使用result變量接收計算結果 result = number1 + number2 print('%d + %d = %d' %(number1,number2,result))sum(1,2)
執(zhí)行結果:C:\python\0\venv\Scripts\python.exe C:/python/0/求和.py1 + 2 = 3Process finished with exit code 0 練習3:加入函數返回值 def sum(number1,number2): '''兩個數字求和''' result = number1 + number2 #可以使用返回值得出計算結果 return result#可以使用變量來接收函數執(zhí)行的返回結果sum_result = sum(1,2)print('計算結果:%d' %sum_result)
執(zhí)行結果: C:\python\0\venv\Scripts\python.exe C:/python/0/求和.py計算結果:3Process finished with exit code 0 注意:return 表示返回,會返回到調用函數的位置,函數內return后續(xù)的代碼不會被執(zhí)行 (3)函數的嵌套 練習4:函數的嵌套 def test1(): print('*' * 50)def test2(): print('-' * 50) test1() print('+' * 50)test2()#打印任意字符任意次數的分隔線def print_line(char,times): print(char * times)print_line('&',40)def print_lines(char,times): ''' 給函數添加文檔注釋:打印多條分割線 :param char:分隔線的字符 :param times:分隔線的次數 ''' row = 1 while row < 3: print_line(char,times) row = row + 1print_lines('!',10)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
執(zhí)行結果:C:\python\0\venv\Scripts\python.exe C:/python/0/函數嵌套.py--------------------------------------------------**************************************************++++++++++++++++++++++++++++++++++++++++++++++++++&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&!!!!!!!!!!!!!!!!!!!!Process finished with exit code 0 (4)模塊中的函數:使用import導入模塊;以py結尾的python源文件都是一個模塊;在模塊中的全局變量和函數都是模塊可直接提供給外界的工具;模塊名也是標識符不能以數字開頭,不能與關鍵字重名,若模塊名以數字開頭則不能導入。 練習5:定義一個函數quadratic(a, b, c),求一元二次方程的方程解 import mathdef quadratic(a,b,c): if a == 0: return TypeError('a不能為0') if not isinstance(a,(int,float)) or not isinstance(b,(int,float)) or not isinstance(c,(int,float)): return TypeError('Bad operand type') delta = math.pow(b,2) - 4*a*c if delta < 0: return '無實根' x1 = math.sqrt((delta)-b)/(2*a) x2 = -math.sqrt((delta)+b)/(2*a) return x1,x2a = int(input('請輸入a:'))b = int(input('請輸入b:'))c = int(input('請輸入c:'))print(quadratic(a,b,c))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
執(zhí)行結果:D:\python\python程序\venv\Scripts\python.exe D:/python/python程序/方程解.py請輸入a:2請輸入b:8請輸入c:4(1.224744871391589, -1.5811388300841898)Process finished with exit code 0 練習6:求n的階乘 def fact(n): return fact_iter(n,1)def fact_iter(num,product): if num == 1: return product return fact_iter(num-1,num * product)print(fact(6))
執(zhí)行結果:D:\python\python程序\venv\Scripts\python.exe D:/python/python程序/階乘.py720Process finished with exit code 0 (5)pyc文件:使用解釋器編譯過的文件,即二進制文件(python解釋器模塊的源碼轉換為字節(jié)碼,這樣當用import導入時可優(yōu)化執(zhí)行速度。 (6)python中數據類型:數字型(整型,浮點型,布爾型,復數),非數字型(字符串,元組,列表,字典) - 列表:多用在處理相同的數據類型,在其他語言中對應數組,用 [ ] 定義,數據之間用逗號隔開,列表的索引即位置標號從0開始,取值若超出索引范圍則會index out of range出錯。
練習7:列表基礎使用 #按Ctrl+Q可以查看光標所在具體使用方法name_list= ['zhangshan','lisi','wangwu']#1.取值和取索引print(name_list[2])print(name_list.index('wangwu'))#使用index方法時,取值必須存在#2.修改指定位置數據,列表指定索引不能超出范圍name_list[1] = '李四'#3.向列表中增加數據name_list.append('三毛') #列表末尾追加數據name_list.insert(1,'喃喃')#在列表指定索引位置插入數據tmp_list = ['哪吒','熬丙','太乙真人']name_list.extend(tmp_list)#將其他列表完整內容追加到當前列表print(name_list)#4.刪除數據name_list.remove('wangwu')#可從列表中刪除指定數據,若數據不只一個,則刪除第一次出現的name_list.pop()#默認刪除列表中最后一個元素name_list.pop(3)#可刪除指定索引位置數據print(name_list)name_list.clear()#清空列表name_list1= ['zhangsan','lii','wang']del name_list1[1]#del 關鍵字本質上是將一個變量從內存中刪除,后續(xù)的代碼則不能再使用這個變量,不建議使用print(name_list1)#統(tǒng)計name_list2 = ['zhangs','lii','wangs','uu','uu']list_len = len(name_list2)print('列表中包含%d個元素' %list_len)print('uu出現了%d次'%name_list2.count('uu'))#排序name_list3 = ['bb','cc','tt','ff']num1_list = [6,3,9,5,2]#升序#name_list3.sort()#num1_list.sort()#降序#name_list3.sort(reverse=True)#num1_list.sort(reverse=True)#逆序name_list3.reverse()num1_list.reverse()print(name_list3)print(num1_list)#打印python中的關鍵字,關鍵字后面不需要括號,如上面的delimport keywordprint(keyword.kwlist)#使用迭代(iteration)遍歷列表,順序從列表獲取數據,每一次循環(huán),數據會保存在name變量name_list4 = ['zhungs','lri','ue']for name in name_list4: print('我的名字叫%s' %name)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
執(zhí)行結果:C:\python\0\venv\Scripts\python.exe C:/python/0/列表.pywangwu2['zhangshan', '喃喃', '李四', 'wangwu', '三毛', '哪吒', '熬丙', '太乙真人']['zhangshan', '喃喃', '李四', '哪吒', '熬丙']['zhangsan', 'wang']列表中包含5個元素uu出現了2次['ff', 'tt', 'cc', 'bb'][2, 5, 9, 3, 6]['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']我的名字叫zhungs我的名字叫l(wèi)ri我的名字叫ueProcess finished with exit code 0 - 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
2.元組:與列表類似,但元組中的變量均不能修改;元組用()定義,數據與數據之間用逗號隔開;元組的索引也從0開始;當元組中只有一個元素時,需要在元素后加入逗號 練習8:元組基礎使用 info_tuple = ('魏無羨',26,1.8)#1.取值和取索引print(info_tuple[0])print(info_tuple.index(1.8))#2.統(tǒng)計計數print(info_tuple.count('魏無羨'))print(len(info_tuple))#3.使用迭代遍歷元組for my_info in info_tuple: print(my_info)#使用格式字符串輸出不方便,因為元組中保存的數據類型不同#4.使用格式化字符輸出,格式化字符后面的‘()’本身就是元組print('%s 年齡是 %d 身高是 %.2f' %('藍忘機',20,1.8))info_tuple1 = ('藍湛',20,1.8)print('%s 年齡是 %d 身高是 %.2f' %info_tuple1)info_str = '%s 年齡是 %d 身高是 %.2f' %info_tuple1 #使用元組可用來拼接新的字符串print(info_str)#元組和列表之間的轉換info_tuple2 = ('魏嬰',26,1.8)print(list(info_tuple2))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
執(zhí)行結果:C:\python\0\venv\Scripts\python.exe C:/python/0/元組.py魏無羨213魏無羨261.8藍忘機 年齡是 20 身高是 1.80藍湛 年齡是 20 身高是 1.80藍湛 年齡是 20 身高是 1.80['魏嬰', 26, 1.8]Process finished with exit code 0 3.字典:存儲多個數據,與列表有序的對象集合不同,字典是無序的;字典用{}定義;用鍵值對存儲數據,鍵值對之間使用逗號分隔;鍵key是索引,值value是數據;鍵和值之間使用冒號分隔;鍵必須唯一;值可取任何數據類型,但鍵只能使用字符串,數字或元組 練習9:字典的基礎使用 #字典是無序的數據集合,輸出的順序與定義的順序無關lanzan = { 'name':'藍湛', 'age': 20, 'gender':True, 'height':1.85 }print(lanzan)weiying_dict = {'name':'魏嬰'}#1.取值print(weiying_dict['name'])#2.增加/修改weiying_dict['age'] = 27print(weiying_dict)weiying_dict['name'] = '魏無羨'print(weiying_dict)#3.刪除weiying_dict.pop('name')print(weiying_dict)#4.統(tǒng)計鍵值個數print(len(lanzan))#5.合并字典tem_dict = {'weight':74.5, 'age': 21}lanzan.update(tem_dict)print(lanzan)#6.清空字典lanzan.clear()print(lanzan)#7.循環(huán)遍歷weiwuxian_dict = {'name':'魏無羨', 'qq':'2423434', 'phone':'3432545'}#k是每一次循環(huán)中獲取到的鍵值對的keyfor k in weiwuxian_dict: print('%s - %s' %(k,weiwuxian_dict[k]))#字典和列表的聯合使用:將多個字典放在一個列表中再進行遍歷card_list = [ {'name':'魏無羨', 'qq':'333333', 'phone':'11111'}, {'name': '藍忘機', 'qq': '222222', 'phone': '88888'},]for card_info in card_list: print(card_info)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
執(zhí)行結果:C:\python\0\venv\Scripts\python.exe C:/python/0/字典.py{'name': '藍湛', 'age': 20, 'gender': True, 'height': 1.85}魏嬰{'name': '魏嬰', 'age': 27}{'name': '魏無羨', 'age': 27}{'age': 27}4{'name': '藍湛', 'age': 21, 'gender': True, 'height': 1.85, 'weight': 74.5}{}name - 魏無羨qq - 2423434phone - 3432545{'name': '魏無羨', 'qq': '333333', 'phone': '11111'}{'name': '藍忘機', 'qq': '222222', 'phone': '88888'}Process finished with exit code 0 - 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
4.字符串:可用雙引號或者單引號定義;len函數統(tǒng)計字符串長度;count統(tǒng)計子字符串在大字符串中出現的次數,若子字符串不存在則次數為0;index統(tǒng)計字符串在大字串中出現的位置,若子字符串不存在程序會報錯。 練習10:字符串的基本使用 str1 = 'hello python'str2 = '我愛看”陳情令''print(str2)print(str1[0])for char in str2: print(char)print(len(str1))print(str1.count('o'))print(str1.index('o'))space_str = ' \t\n\r' #判斷空白字符print(space_str.isspace())num_str = '\u00b2'#判斷字符串是否只包含數字,下列三種均不能判斷小數print(num_str)#平方print(num_str.isdecimal())#只能判斷單純的數字print(num_str.isdigit())#可判斷單純數字和unicode的數字print(num_str.isnumeric())#可判斷單純數字,中文數字和unicode的數字hell_str = 'hello world'print(hell_str.startswith('Hello'))#判斷是否以字符串開始print(hell_str.endswith('world'))#判斷是否以字符串結束print(hell_str.find('o'))#判斷子字符串在字符串中的位置,與index的區(qū)別在于當查找的字符不存在時不報錯print(hell_str.replace('world','boji'))#替換字符串,會返回新字符串,但注意不會改變原有字符串print(hell_str)poem = ['\t\n白日依', '黃河', '入了海流\t\n']for poem_str in poem: print('|%s|'% poem_str.strip().center(10,' '))#strip去除空白字符,center中心對齊;ljust向左對齊;rjust向右對齊poem1 = '燈管\t 王之渙 \t白日依山盡 \t \n黃河'poem_list = poem1.split()#拆分字符串print(poem_list)result = ' '.join(poem_list)print(result)#切片方法適用于字符串,列表,元組,可采用倒序順序方法#字符串[開始索引:結束索引:步長]num_str = '01234567'print(num_str[2:6])print(num_str[2:])print(num_str[:6])print(num_str[-1:])print(num_str[:])print(num_str[::2])print(num_str[::-1])
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
C:\python\0\venv\Scripts\python.exe C:/python/0/字符串.py我愛看”陳情令'h我愛看”陳情令'1224True2FalseTrueTrueFalseTrue4hello bojihello world| 白日依 || 黃河 || 入了海流 |['燈管', '王之渙', '白日依山盡', '黃河']燈管 王之渙 白日依山盡 黃河2345234567012345701234567024676543210Process finished with exit code 0 - 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
|