Python編程基礎-練習代碼合集


1.初識Python

  • 猜數字游戲

 1 from random import randint
 2 
 3 
 4 def play():
 5     random_int = randint(0, 100)
 6 
 7     while True:
 8         user_guess = int(input("請輸入可猜測的數字(0-100):"))
 9 
10         if user_guess == random_int:
11             print(f"你找到了數字({random_int})太厲害了!")
12             break
13 
14         if user_guess < random_int:
15             print("猜小啦!")
16             continue
17 
18         if user_guess > random_int:
19             print("猜大啦!")
20             continue
21 
22 
23 if __name__ == '__main__':
24     play()
View Code

2.Python語法基礎

  • 求矩形面積

1 # rect_length = 6
2 # rect_width = 3
3 # rect_area = rect_length * rect_width
4 # print('長方形的面積是:', rect_area)
5 
6 rect_length = float(input("請輸入矩形的長(cm):"))
7 rect_width = float(input("請輸入矩形的寬(cm):"))
8 rect_area = rect_length * rect_width
9 print('長方形的面積是:', rect_area)
求矩形面積

  •  運算符優先級

 1 # print(24 + 12 / 6 ** 2 * 18)  # 6 ** 2 指的是6 的二次方
 2 # print(24 + 12 / (6 ** 2) * 18)
 3 # print(24 + (12 / (6 ** 2)) * 18)
 4 # print(24 + (12 / 6) ** 2 * 18)
 5 # print((24 + 12) / 6 ** 2 * 18)
 6 # print(-4 * 5 + 3)
 7 # print(4 * - 5 + 3)
 8 
 9 print(15 + -20 - 2 ** 3)  # 結果=-13
10 # 先算2的3次方,再從左往右進行加減,其中-20表示負20,即15減20
11 
12 
13 print(5 % 2 + 3 // 2 - 2 * 6 / 12)  # 結果=1.0
14 # 由於運算符的優先級,此式子等同於:
15 # print((5 % 2) + (3 // 2) - (2 * 6 / 12))
16 # 其中,%表示求余數(5除2等2余1,結果取1),//表示取整除(3除2等於1.5,結果取1)
17 
18 
19 print(4 & 4 >> 1)  # 結果=0
20 # 由於運算符的優先級,此式子等同於:
21 # print(4 & (4 >> 1))
22 # 其中,4 >> 1 = 2,4 & 2 =0
23 
24 
25 print(2 <= 3 ^ 2)
26 # 由於運算符的優先級,此式子等同於:
27 # print(2 <= (3 ^ 2))
28 # 其中,3 ^ 2 =1,2 <= 1 為False
29 
30 
31 a = 3 != 2
32 print(a)
33 # 由於運算符的優先級,此式子等同於:
34 # a = (3 != 2)
35 # print(a)   為True
36 print('----------')
37 
38 a = 11
39 b = 11
40 print(a is b)
41 
42 List = [1, 2, 3.0]
43 print(1 in List)
44 
45 A = True
46 B = False
47 print(A and B)
View Code

 

  •  明文密文

1 message = input('請輸入一個字母:')
2 m_Pwd = chr(ord(message) + 3)  # 將數輸入的字母轉換成數字加3后在轉回字母,結果為: d
3 print('明文:', message)
4 print('密文:', m_Pwd)
5 m_Pwd_jm = chr(ord(m_Pwd) - 3)
6 print('解密:')
7 print('密文:', m_Pwd)
8 print('解密的明文:', m_Pwd_jm)
View Code

  • 凱撒密碼

 1 # -*- coding: utf-8 -*-
 2 
 3 # @Date    : 2018-10-12
 4 # @Author  : Peng Shiyu
 5 
 6 class CaesarCipher(object):
 7     """
 8     凱撒加密解密
 9     """
10 
11     def __crypt(self, char, key):
12         """
13         對單個字母加密,偏移
14         @param char: {str} 單個字符
15         @param key: {num} 偏移量
16         @return: {str} 加密后的字符
17         """
18         if not char.isalpha():
19             return char
20         else:
21             base = "A" if char.isupper() else "a"
22             return chr((ord(char) - ord(base) + key) % 26 + ord(base))
23 
24     def encrypt(self, char, key):
25         """
26         對字符加密
27         """
28         return self.__crypt(char, key)
29 
30     def decrypt(self, char, key):
31         """
32         對字符解密
33         """
34         return self.__crypt(char, -key)
35 
36     def __crypt_text(self, func, text, key):
37         """
38        對文本加密
39        @param char: {str} 文本
40        @param key: {num} 偏移量
41        @return: {str} 加密后的文本
42        """
43         lines = []
44         for line in text.split("\n"):
45             words = []
46             for word in line.split(" "):
47                 chars = []
48                 for char in word:
49                     chars.append(func(char, key))
50                 words.append("".join(chars))
51             lines.append(" ".join(words))
52         return "\n".join(lines)
53 
54     def encrypt_text(self, text, key):
55         """
56         對文本加密
57         """
58         return self.__crypt_text(self.encrypt, text, key)
59 
60     def decrypt_text(self, text, key):
61         """
62         對文本解密
63         """
64         return self.__crypt_text(self.decrypt, text, key)
65 
66 
67 if __name__ == '__main__':
68     plain = """
69     you know? I love you!
70     """
71     key = 3
72 
73     cipher = CaesarCipher()
74 
75     # 加密
76     print(cipher.encrypt_text(plain, key))
77     # brx nqrz? L oryh brx!
78 
79     # 解密
80     print(cipher.decrypt_text("brx nqrz? L oryh brx!", key))
81     # you know? I love you!
View Code

  • 凱撒密碼2

 1 '''
 2 A:65
 3 Z:90
 4 a:97
 5 z:122
 6 0:48
 7 9:57
 8 '''
 9 
10 old_message = input("please input your message:")
11 new_message = ''
12 for old_c in old_message:  # old_c是從明文中取出的字符
13     if 'A' <= old_c <= 'Z':
14         new_c = chr((ord(old_c) - ord('A') + 3) % 26 + ord('A'))
15     elif 'a' <= old_c <= 'z':
16         new_c = chr((ord(old_c) - ord('a') + 3) % 26 + ord('a'))
17     elif '0' <= old_c <= '9':
18         new_c = chr((ord(old_c) - ord('0') + 3) % 10 + ord('0'))
19     else:
20         new_c = old_c
21     new_message += new_c  # new_message=new_message+new_c
22 print("the encrypted message is %s" % (new_message))
23 # 解密
24 old_message = ''
25 for new_c in new_message:  # new_c是從密文中取出的字符
26     if 'A' <= new_c <= 'Z':
27         old_c = chr((ord(new_c) - ord('A') - 3) % 26 + ord('A'))
28     elif 'a' <= new_c <= 'z':
29         old_c = chr((ord(new_c) - ord('a') - 3) % 26 + ord('a'))
30     elif '0' <= new_c <= '9':
31         old_c = chr((ord(new_c) - ord('0') - 3) % 10 + ord('0'))
32     else:
33         old_c = new_c
34     old_message += old_c
35 print("the decrypted message is %s" % (old_message))
View Code

 

  •  計算圓形的各參數

 1 import math
 2 
 3 # 1.輸入圓的半徑
 4 radius = float(input("請輸入圓的半徑(cm):"))
 5 circle_C = math.pi * 2 * radius
 6 circle_Area = math.pi * math.pow(radius, 2)
 7 # 輸出周長和面積
 8 print("圓的半徑是:", radius, "cm")
 9 print("圓的周長是:,{} \"cm\"".format('%.2f' % circle_C))
10 print("圓的面積是:, {} \"c㎡\"".format('%.2f' % circle_Area))
11 print('------分割線------')
12 
13 # 2.輸入面積
14 circle_Area = float(input("請輸入圓的面積(c㎡):"))
15 radius = math.sqrt(circle_Area / math.pi)
16 circle_C = math.pi * 2 * radius
17 # 輸出半徑和周長
18 print("圓的面積是:, {} \"c㎡\"".format('%.2f' % circle_Area))
19 print("圓的半徑是:, {} \"cm\"".format('%.2f' % radius))
20 print("圓的周長是:,{} \"cm\"".format('%.2f' % circle_C))
21 print('------分割線------')
22 
23 # 3.輸入周長
24 circle_C = float(input("請輸入圓的周長(cm):"))
25 radius = circle_C / (math.pi * 2)
26 circle_Area = math.pi * math.pow(radius, 2)
27 print("圓的周長是:,{} \"cm\"".format('%.2f' % circle_C))
28 print("圓的半徑是:, {} \"cm\"".format('%.2f' % radius))
29 # 輸出半徑和周長
30 print("圓的面積是:, {} \"c㎡\"".format('%.2f' % circle_Area))
View Code

 

  • 回文數

1 number = input('請輸入一個數:')
2 s1 = number[::-1]
3 # print(s1)
4 if number == s1:
5     print("您輸入的'{0}'是回文數".format(number))
6 else:
7     print("您輸入的'{0}'不是回文數".format(number))
View Code

 

  •  輸出星座

 1 """
 2 實訓1 對用戶星座進行分析並輸出結果
 3 """
 4 print('-----星座小程序------')
 5 name = input("請輸入您的名字:")
 6 print('星座日期對應表:')
 7 print("編號\t\t星座\t\t日期  \n"
 8       "1\t\t水瓶\t\t1月20~2月18\n"
 9       "2\t\t雙魚\t\t2月19~3月20\n"
10       "3\t\t白羊\t\t3月21~4月19\n"
11       "4\t\t金牛\t\t4月20~5月20\n"
12       "5\t\t雙子\t\t5月21~6月21\n"
13       "6\t\t巨蟹\t\t6月21~7月22\n"
14       "7\t\t獅子\t\t7月23~8月22\n"
15       "8\t\t處女\t\t8月23~9月22\n"
16       )
17 print(name, ",您好!請根據如上提示選擇編號:")
18 number = input()
19 if number == '1':
20     print(name, ',您好!水瓶座的您星座分析結果:編號:1\t星座:水瓶座\t日期:1月20~2月18\n')
21 
22 elif number == '2':
23     print(name, ',您好!雙魚座的您星座分析結果:編號:2\t星座:雙魚座\t日期:2月19~3月20\n')
24 elif number == '3':
25     print(name, ',您好!白羊座的您星座分析結果:編號:3\t星座:白羊座\t日期:3月21~4月19\n')
26 elif number == '4':
27     print(name, ',您好!金牛座的您星座分析結果:編號:4\t星座:金牛座\t日期:4月20~5月20\n')
28 elif number == "5":
29     print(name, ',您好!雙子座的您星座分析結果:編號:5\t星座:雙子座\t日期:5月21~6月21\n')
30 elif number == '6':
31     print(name, ',您好!巨蟹座的您星座分析結果:編號:6\t星座:巨蟹座\t日期:6月21~7月22\n')
32 elif number == '7':
33     print(name, ',您好!獅子座的您星座分析結果:編號:7\t星座:獅子座\t日期:7月23~8月22\n')
34 elif number == '8':
35     print(name, ',您好!處女座的您星座分析結果:編號:8\t星座:處女座\t日期:8月23~9月22\n')
36 else:
37     print('您的輸入有誤!')
View Code

 

 

  •  字符串操作

 1 s = "12,34,45,54 "
 2 a = s.split(",")
 3 print(a)
 4 
 5 w = 'waiter'
 6 print(w.strip('inger'))
 7 
 8 w = 'running'
 9 print(w.strip("ing"))
10 
11 w = 'ingrunning'
12 print(w.rsplit('ing'))
View Code

  •  格式化輸出成績

 1 Class = input('請輸入您的班級:')
 2 stu_name = input('請輸入您的學生名:')
 3 score1 = float(input('請輸入您第1門課程的成績:'))
 4 score2 = float(input('請輸入您第2門課程的成績:'))
 5 score3 = float(input('請輸入您第3門課程的成績:'))
 6 AVG = (score1 + score2 + score3) / 3
 7 
 8 # print('\'{}\'的\'{}\'的第1門課程成績是{},第2門課程成績是{},第3門課程成績是{},平均成績是{}'
 9 #       .format(Class, stu_name, score1, score2, score3, '%.2f' % AVG))
10 
11 # print('\'%s\'的\'%s\'的第1門課程成績是%f,第2門課程成績是%f,第3門課程成績是%f,平均成績是%.2f'
12 #       % (Class, stu_name, score1, score2, score3, AVG))
13 
14 print(f'\'{Class}\'的\'{stu_name}\'的第1門課程成績是{score1},第2門課程成績是{score2},第3門課程成績是{score3},平均成績是{AVG:.2f}')
View Code

 

  • 格式化輸出

 1 print("我叫%s,今年%d歲!" % ('小明', 10))
 2 print("{} a word she can get what she {} for.".format('With', 'came'))  # 使用{}
 3 print('{pre} a word she can get what she {verb} for.'.format(pre='With', verb='came'))  # 通過關鍵字參數
 4 print('{0} a word she can get what she {1} for.'.format('With', 'came'))  # 通過位置
 5 p = ['With', 'came']
 6 print('{0[0]} a word she can get what she {0[1]} for.'.format(p))  # 通過下標索引
 7 # 相當於:
 8 print(p[0] + '' + ' a word she can get what she ' + p[1] + ' for.')
 9 
10 # 通過復制
11 city = '廣州'
12 url = 'http://www.baidu.com={}'.format(city)
13 print(url)
14 
15 print('{:.2f}'.format(321.33345))  # 必須要冒號
16 print('{:,}'.format(1234567890))  # ,逗號作金額的千位分隔符
17 print('{:b}'.format(17))  # 2進制
18 print('{:d}'.format(17))  # 10進制
19 print('{:o}'.format(17))  # 8進制
20 print('{:x}'.format(17))  # 16進制
View Code

 

  •  字符型內建函數練習

 1 # 其他:
 2 s = "I love python!"
 3 print(s.count("o"))
 4 print(s.count("love"))
 5 print(s.index("y"))  # index(sub)
 6 print(s.endswith("Python!"))
 7 print(s.endswith("python!"))
 8 print(s.startswith("I"))
 9 print("o在")
10 
11 print(s.replace("python", "Java"))
12 print(s.capitalize())  # 一句話中的首字母大寫
13 print(s.title())  # 每個字符串首字母大寫
14 print(s.upper())  # 每個字母都大寫
15 print(s.isalpha())  # 判斷字符串是不是單純的字母
16 print(s[::-1])
17 # 回文數
18 s = "12321"
19 s1 = s[::-1]
20 if s == s1:
21     print("True")
22 else:
23     print("False")
24 
25 print('-----分割線-----')
26 # 練習:
27 # 學史明理、學史增信、學史崇德、學史力行,以實際行動繼承和弘揚“五四精神”
28 
29 # Sentence = '學史明理、學史增信、學史崇德、學史力行,以實際行動繼承和弘揚”五四精神“'
30 # Sentence.count("學史")
31 # print("“學史”出現的次數是:", Sentence.count("學史"))
32 # print("句子是是否存在“五四精神”這個詞:", Sentence.endswith("”五四精神“"))
33 
34 s = "學史明理、學史增信、學史崇德、學史力行,\
35 以實際行動繼承和弘揚“五四精神”"
36 substr = "學史"
37 count = s.count(substr)
38 print("\"{0}\"在\"{1}\"中出現的次數是:{2}".format(substr, s, count))
39 
40 sub2 = "五四精神"
41 isFind = False
42 if s.find(sub2) != -1:
43     isFind = ""
44 print("\"{0}\"在\"{1}\"中是否存在:{2}".format(sub2, s, isFind))
View Code

  • 操作運算符練習

 1 """
 2 1.算術運算符
 3 2.比較運算符
 4 3.賦值運算符
 5 4.按位運算符
 6 5.邏輯運算符
 7 6.成員運算符
 8 7.身份運算符
 9 """
10 # 1.算術運算符
11 print('1.算術運算符')
12 print(2 / 1)  # 單斜杠除法
13 print(type(2 / 1))
14 print(2 // 1)
15 print(type(2 // 1))  # 雙斜杠除法
16 
17 print(1 + 2, 'and', 1.0 + 2)  # 加法和乘法
18 print(1 * 2, 'and', 1.0 * 2)
19 print('23除以10,商為:', 23 // 10, ',余數為:', 23 % 10)  # 商和與余數
20 print(3 * ' Python')  # 字符串的n次重復
21 print('       ')
22 print('2.比較運算符')
23 #
24 print(1 == 2)
25 print(1 != 2)
26 print('下面是字符的比較:')
27 print('a' == 'b', 'a' != 'b')
28 print('a' < 'b', 'a' > 'b')
29 print(ord('a'), ord('b'))  # 查看字母編碼
30 print(chr(97), chr(98))  # 查看編碼對應的字符
31 print('下面是符號的比較:')
32 print('# ' < '$')
33 print('       ')
34 print('3.賦值運算符')
35 # 3.賦值運算符
36 a = 1 + 2
37 print(a)
38 print('a:', a)
39 a += 4
40 print('a += 4 特殊賦值運算后,a:', a)
41 # f += 4
42 # print(f)
43 
44 print('       ')
45 print('4.按位運算符')
46 # 4.按位運算符
47 a = 60
48 b = 13
49 print('a (60) 的二進制:0011 1100')
50 print('b (13) 的二進制:0000 1101')
51 print('a & b :', a & b)
52 print('a | b :', a | b)
53 print('a ^ b :', a ^ b)
54 print('~a :', ~a)
55 print('a << 2 :', a << 2)
56 print('a >> 2 :', a >> 2)
57 print('       ')
58 print('5.邏輯運算符')
59 # 5.邏輯運算符
60 a = 11
61 b = 22
62 print('a = 11,b = 22')
63 print('a and b :', a and b)
64 print('a or b :', a or b)
65 print('not(a and b) :', not (a and b))
66 print('       ')
67 print('6.成員運算符')
68 # 6.成員運算符
69 List = [1, 2, 3.0, [4, 5], 'Python3']
70 print(1 in List)  # 查看1是否在列表內
71 print([1] in List)  # 查看[1]是否在列表內
72 print(3 in List)
73 print([4, 5] in List)
74 print('Python' in List)
75 print('Python3' in List)
76 print('       ')
77 print('7.身份運算符')
78 # 7.身份運算符
79 a = 11
80 b = 11
81 print('a = 11,b =11')
82 print('a is b :', a is b)
83 print('a is not b :', a is not b)
84 print(id(a))  # 查看id地址
85 print(id(b))
86 a = 11
87 b = 22
88 print('a = 11,b = 22')
89 print('a is b :', a is b)
90 print('a is not b :', a is not b)
91 print(id(a))
92 print(id(b))
View Code

 

 

 

 

  • 邏輯運算符例子

1 # 邏輯運算例子
2 a, b = 1, 22
3 print("a and b:", a and b)
4 print("a or b :", a or b)
5 print("not b:", not b)

  •  列表、元組---->轉字符串

 1 str = "1,2,3,4,5"
 2 new_str = str.split(",")
 3 # print(new_str,type(new_str)) # ['1', '2', '3', '4', '5'] <class 'list'>
 4 
 5 # 將列表、元組轉換成字符串
 6 L = ['1', '2', '3', '4', '5']
 7 T = ('1', '2', '3', '4', '5')
 8 print(L, type(L), "\n", T, type(T))
 9 L_join = ",".join(L)
10 T_join = ",".join(T)
11 print("\n轉換后:")
12 print(L_join, type(L_join))  # 1,2,3,4,5 <class 'str'>
13 print(T_join, type(T_join))
View Code

 

 

  •  作業

  實訓1

  

 1 # -*-coding:utf-8-*-
 2 # 1.實訓1:統計“溫暖”,“活動”出現的次數。
 3 # 2.將字符串“2020年1月14日至18日”中的數字轉化成整數類型並計算結果。
 4 # Str = '2020年1月14日至18日,學校2020年“溫暖點亮夢想,青春不負韶華”送溫暖活動之走訪慰問學生家庭活動順利開展。'
 5 Str = input('請輸入一段字符串:')  # 輸入語句
 6 word1 = '溫暖'  # 用一個變量保存需要提取的字符串
 7 word2 = '活動'
 8 count1 = Str.count(word1)  # 統計字符串出現次數的方法.count()
 9 count2 = Str.count(word2)
10 print('\"{0}\"在\"{1}\"中出現的次數是:{2}'.format(word1, Str, count1))  # 格式化輸出
11 print('\"{0}\"在\"{1}\"中出現的次數是:{2}'.format(word2, Str, count2))
12 
13 number1 = int(Str[0:4])  # 按索引提取需要的字符串並轉換成整型
14 number2 = int(Str[5:6])
15 number3 = int(Str[7:9])
16 number4 = int(Str[11:13])
17 total = number1 + number2 + number3 + number4  # 轉換后的數據相加並用total變量保存
18 sentence = Str[0:14]  # 提取字符串“2020年1月14日至18日”並用sentence變量保存
19 print('"{0}"字符串的計算結果:{1}+{2}+{3}+{4}={5}'.format(sentence, number1, number2, number3, number4, total))  # 格式化輸出
View Code

   實訓2 

  

 1 # -*-coding:utf-8-*-
 2 # 1.均值:
 3 import math
 4 
 5 num1 = float(input('請輸入第1個數:'))
 6 num2 = float(input('請輸入第2個數:'))
 7 num3 = float(input('請輸入第3個數:'))
 8 average_value = (num1 + num2 + num3) / 3
 9 # 2.方差
10 variance = ((num1 - average_value) ** 2 + (num2 - average_value) ** 2 + (num3 - average_value) ** 2) / 3
11 
12 # 3.標准差
13 standard_deviation = math.sqrt(variance)
14 
15 print('您輸入的"{0},{1},{2},"的均值為:{3},方差為:{4},標准差為:{5}'
16       .format(num1, num2, num3, average_value, variance, standard_deviation))  # 格式化輸出
View Code

 

   numpy方式

  

 1 # -*-coding:utf-8-*-
 2 # 實訓2:  通過表達式計算3個數值的均值,方差,標准值
 3 
 4 def get_mean_var_std(arr):
 5     import numpy as np
 6 
 7     # 求均值
 8     arr_mean = np.mean(arr)
 9     # 求方差
10     arr_var = np.var(arr)
11     # 求標准差
12     arr_std = np.std(arr, ddof=1)
13     print("平均值為:%f" % arr_mean)
14     print("方差為:%f" % arr_var)
15     print("標准差為:%f" % arr_std)
16 
17     return arr_mean, arr_var, arr_std
18 
19 
20 if __name__ == '__main__':
21     arr = [11, 2, 5]
22     print(get_mean_var_std(arr))
View Code

 

 

 

   實訓3

  

 1 # -*-coding:utf-8-*-
 2 # Python實現字符串格式化輸出的方法 (3種)
 3 # 1.% 2.format 3.格式化f
 4 # 第1種:
 5 name = input('請輸入您的名字:')
 6 print('您好,%s先生,您喜歡Python嗎?' % (name))
 7 
 8 # 第2種:
 9 Like = input()
10 print('你真的{}?'.format(Like))
11 
12 # 第3種:
13 answer = input()
14 print(f'{answer}的話就去搬磚吧!')
View Code

 

3.Python數據結構

列表

  • 求學生成績

 1 # 1.輸入數據:
 2 stu_score_s = input('請輸入您的成績(成績用逗號分隔):')  # 輸入的數據是字符串類型
 3 # 2.分離數據得到數據列表:
 4 stu_score_s_L = stu_score_s.split(",")
 5 # print(stu_score_s_L)
 6 
 7 # 3.讀取數據列表中的數據進行累加,求平均值
 8 total = 0  # 初始化總成績為0
 9 score_Max = int(stu_score_s_L[0])  # 將列表中的第一個數保存到max中
10 score_L = len(stu_score_s_L)  # 列表長度
11 
12 for i in range(0, score_L):  # 從0到len(L),i用來做列表的索引號 range函數產生一組自然數序列
13     # 循環取數據並進行累加
14     total += int(stu_score_s_L[i])  # 把字符串類型轉換為int類型
15 score_Avg = total / score_L  # 求平均成績
16 
17 # 求最大值:
18 for i in range(0, score_L):
19     stu_score_s_L[i] = int(stu_score_s_L[i])
20     if stu_score_s_L[i] > score_Max:  # 比較最大值
21         score_Max = stu_score_s_L[i]  # 替換最大值
22 
23 # 求偶數和:
24 total_even = 0
25 for i in range(0, score_L):
26     # 循環讀取數據並進行偶數累加
27     stu_score_s_L[i] = int(stu_score_s_L[i])  # 強制類型轉換
28     if stu_score_s_L[i] % 2 == 0:  # 判斷是否是偶數
29         total_even += stu_score_s_L[i]  # 偶數和累加
30 
31 # 4.顯示平均成績,最大值,偶數和:
32 print('您的平均成績是:{0:.1f}'.format(score_Avg))
33 print('您的最高成績是:{0:.1f}'.format(score_Max))
34 print('您的偶數和成績是:{0:.1f}'.format(total_even))
View Code

 

  • 求學生成績(列表)

 1 # 1.輸入數據:
 2 stu_score_s = input('請輸入您的成績(成績用逗號分隔):')
 3 # 2.分離數據得到數據列表:
 4 stu_score_s_L = stu_score_s.split(",")
 5 # print(stu_score_s_L)
 6 
 7 # 3.讀取數據列表中的數據進行累加,求平均值
 8 total = 0  # 初始化總分為0
 9 score_L = len(stu_score_s_L)  # 用戶所輸入的數據列表的長度
10 for i in range(0, score_L):  # 遍歷數據列表中的每個數字
11     total += float(stu_score_s_L[i])
12     score_Avg = total / score_L
13     # 4.顯示平均成績
14 print('您的平均成績是:{0:.1f}'.format(score_Avg))
View Code

 

  • 求列表元素最大和最小值

1 nums = [18, 39, 11, 34, 51, 100, 69, 71, 92, 88, 5, 75]
2 nums.sort()
3 max = nums[len(nums) - 1]
4 min = nums[0]
5 print("最大值:", max)
6 print("最小值", min)
View Code

 

  •  列表索引訪問和切片range()函數練習

 

字符串---->列表

 

 

 

 

 

 

1 L = input('請輸入一組奇數:').split(",")
2 for i in L:
3     num = int(i)
4     if num % 2 == 1:
5         print("您輸入的數是奇數,數據為:", num)

 

 

 

元組--->列表

 

切片

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

函數形式切片

 1 mynumlist = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
 2 def qiepian(x, y):
 3     result = mynumlist[x:y]
 4     return print(result)
 5 
 6 
 7 def qiepian2(x, y, z):
 8     result2 = mynumlist[x:y:z]
 9     return print(result2)
10 
11 
12 def qiepian3(x, y):
13     result3 = mynumlist[x::y]
14     return print(result3)
15 
16 
17 qiepian(2, 7)  # [30, 40, 50, 60, 70]
18 qiepian3(2, 1)  # [30, 40, 50, 60, 70, 80, 90, 100]
19 qiepian(0, 0)  # []
20 qiepian2(0, 0, 3)  # []
View Code

 range()

 

  • list.sort()和簡單判斷

 1 L = [23, 2, 6, 54, 65]
 2 print(L)
 3 L.sort() # 改變內容
 4 print(L)
 5 L.sort(reverse=True) # 反轉
 6 print(L)
 7 
 8 for i in L:
 9     if i % 2 == 0:
10         print(i)
11     if 89 in L:
12         print(89)
13 else:
14     print('89不存在!')
View Code

 

  •  任務實現

1 # 使用方括號創建列表對象['pen','paper',10,False,2.5],並賦值給變量task_tuple
2 task_tuple = ['pen', 'paper', 10, False, 2.5]
3 print(type(task_tuple))  # 查看當前變量數據類型
4 task_tuple = tuple(task_tuple)  # 將變量task_tuple轉換成元組類型
5 print(type(task_tuple))  # 查看轉換后的變量數據類型
6 Index = task_tuple.index(False)  # 查詢元素位置索引
7 bool = task_tuple[Index]  # 提取元組元素
8 print(bool)  # 查看提取元素
View Code

 1 # -*- coding:utf-8 -*-
 2 task_list = [110, 'dog', 'cat', 120, 'apple']
 3 task_list.insert(2, [])
 4 # task_list.pop()
 5 task_list.remove('apple')
 6 num_index1 = task_list.index(110)  # 查詢元素位置
 7 num_index2 = task_list.index(120)
 8 # print(task_list[num_index1]) #110
 9 # print(task_list[num_index2]) #120
10 task_list[num_index1] *= 10  # 將查詢出來的元素進行自乘運算並賦值修改
11 task_list[num_index2] *= 10
12 print(task_list)
View Code

  •  作業

 1 # 在列表[110,’henry’,’joel’,’java’,76,’english’,89]中插入一個空列表,
 2 # 刪除名字字符串‘joel’,同時查找表中的數值並在列表中增大1.2倍。
 3 
 4 List = [110, 'henry', 'joel', 'java', 76, 'english', 89]
 5 print('修改前的列表為:',List)
 6 L_none = []
 7 List.append(L_none)
 8 List.remove('joel')
 9 num_index = List.index(110)
10 List[num_index] *= 1.2
11 num_index = List.index(76)
12 List[num_index] *= 1.2
13 num_index = List.index(89)
14 List[num_index] *= 1.2
15 print('修改后的列表為:',List)
View Code

 1 def Fibonacci(n):
 2     if n <= 0:
 3         return 0
 4     elif n == 1:
 5         return 1
 6     else:
 7         return Fibonacci(n - 1) + Fibonacci(n - 2)
 8 
 9 
10 def Fibonacci_Recursion(n):
11     result_list = [0, 1]
12     for i in range(2, n + 1):
13         result_list.append(Fibonacci(i))
14     result_list.pop(2)
15     list_sum = sum(result_list)
16     print("列表數據之和=%d" % list_sum)
17     return result_list
18 
19 
20 print("列表=%s" % Fibonacci_Recursion(5))
View Code

 

 

元組

  • 元組基本操作練習

切片

 

 

 

元組--->列表

 

 

 

列表--->元組

 

 

 元組解包

 

 

 元組sorted()排序后變成列表

 

 

 其他操作

  • 實訓

 1 # 用戶自定義查詢菜單,輸出查詢結果
 2 Str = '\n請選擇需要進行操作的對應數字:\n查詢漢堡類菜單---1\n查詢小食類菜單---2\n查詢飲料類菜單---3\n' \
 3       '不查詢---0:\n'
 4 food_Type = ("漢堡類", "小食類", "飲料類")  # 索引:0,1,2
 5 ham_Details = ("香辣雞腿堡", "勁脆雞腿堡", "新奧爾良烤雞腿堡", "半雞半蝦堡")
 6 snacks_Details = ("薯條", "黃金雞塊", "香甜粟米棒")
 7 drink_Details = ("可口可樂", "九珍果汁", "經典咖啡")
 8 
 9 while True:
10     print(Str)
11     number = int(input())
12     if number == 1:
13         print(food_Type[number - 1])
14         print(ham_Details)
15     elif number == 2:
16         print(food_Type[number - 1])
17         print(snacks_Details)
18     elif number == 3:
19         print(food_Type[number - 1])
20         print(drink_Details)
21     elif number == 0:
22         print("感謝您的使用!歡迎下次光臨!")
23         break
24     else:
25         print("請輸入有效的數字編號!")
View Code

 

字典

  • 基本操作

 

 

集合

  • 基本操作

增:

 

 

 

 刪:

4.流程控制語句

  • 輸出學生成績及獲獎等級

輸入8個成績,逗號分隔,去除最高最低成績,輸出學生成績平均值和獲獎等級

 1 # 目標:一行輸入8個成績,去除最高和最低成績,輸出平均成績和獲獎等級
 2 # 1.輸入數據
 3 while True:
 4     try:
 5         score_s = input('請輸入評委給出的成績(成績用逗號分隔):')
 6         score_Ls = score_s.split(',') # 字符串轉列表
 7         # 方法1:
 8         score_LI = []  # 用來保存轉換為整型的成績
 9         for i in score_Ls:
10             score_LI.append(int(i))
11         # 方法2:
12         score_LI = [int(i) for i in score_Ls]  # 列表解析式[表達式 for x in iteralbeobject 條件表達式]
13     except ValueError:  # 產生異常,顯示輸入數據錯誤
14         print("輸入成績數據錯誤,請重新輸入!")
15     else:
16         # 2.數據處理
17         # 2.1 在列表中刪除最大值
18         max_L = max(score_LI)
19         score_LI.remove(max_L)
20         # 2.1 在列表中刪除最小值
21         min_L = min(score_LI)
22         score_LI.remove(min_L)
23 
24         # 2.3求平均值
25         score_ave = sum(score_LI) / len(score_LI)
26         # 2.4 根據平均值進行划分
27         grade = '無獎'
28         if score_ave >= 90:
29             grade = '一等獎'
30         elif score_ave >= 80:
31             grade = '二等獎'
32         elif score_ave >= 70:
33             grade = '三等獎'
34         elif score_ave >= 60:
35             grade = '優勝獎'
36         # 3.顯示結果
37         print('平均成績是{:.2f}的學生的獲獎等級是:{}'.format(score_ave, grade))
38         break
View Code

  •  冒泡排序

 1 # 1.用戶輸入:
 2 mls = input("請輸入一組數據(用逗號分隔):")
 3 ml = [int(i) for i in mls.split(",")]  # 准備好列表數據
 4 
 5 j = 0  # 初始化j=0,j表示第幾輪
 6 while j < len(ml):
 7     count = 0  # 初始化交換器=0
 8     i = 0  # 初始化i=0
 9     while i < len(ml) - 1:
10         if ml[i] > ml[i + 1]:
11             ml[i], ml[i + 1] = ml[i + 1], ml[i]
12             count += 1
13         i += 1
14     if count == 0:
15         break
16     j += 1
17 print("排序后的結果是:", ml)
View Code

 

 

  •  列表解析式

1 a = [i ** 2 for i in range(0, 10) if i % 2 == 0]
2 print(a)
3 
4 ml = list(map(int, input("請輸入一組數據(逗號分隔):").split(",")))
5 print(ml)

 

  •  判斷素數

 1 # 編程:判斷輸入的一個數是否是素數(質數),不是素數則循環,輸出素數則停止循環
 2 # 只能被自己和1整除的數
 3 while True:
 4     num = int(input("請輸入一個整數:(大於1)"))
 5     if num == 0:
 6         exit(0)
 7     isPriss = True
 8     count = 0
 9     for i in range(2, num // 2 + 1):  # 迭代要去除的數
10         # count += 1
11         if num % i == 0:
12             print("{}不是質數,{}={}*{}".format(num, num, i, num // i))
13             isPriss = False
14     # 退出for代碼,有兩種可能,一種是迭代結束,是質數,一種break跳出for
15     if isPriss:
16         print("{}是質數".format(num))
17         break
18     # print("count=", count)
View Code

  •  判斷素數2

 1 # 編程:判斷輸入的一個數是否是素數(質數)
 2 # 只能被自己和1整除的數
 3 num = (input("請輸入一組整數:數字大於1,數字間用逗號隔開:"))
 4 num_L = [int(i) for i in num.split(",")]
 5 for num in num_L:  # num從輸入的數據列表中取得的一個數
 6     # 判斷num是否是一個質數
 7     isPriss = True
 8     # count = 0
 9     for i in range(2, num // 2 + 1):  # 迭代要去除的數
10         # count += 1
11         if num % i == 0:
12             print("{}不是質數×,{}={}*{}".format(num, num, i, num // i))
13             isPriss = False
14             break
15     # 退出for代碼,有兩種可能,一種是迭代結束,是質數,一種break跳出for
16     if isPriss:
17         print("{}是質數√".format(num))
View Code

 

  •  回文數

 1 # 目標:輸入一個正整數;輸出:M位的回文數共有幾個,這些回文數中有幾個包含數字99
 2 # 1.構造M位數的列表
 3 # 1.1用戶輸入位數M
 4 m = int(input('請輸入一個正整數:'))
 5 
 6 # 1.2構造m位的列表
 7 m_L = list(range(10 ** (m - 1), 10 ** m))
 8 
 9 # 2.找有多少個回文數?包含99的多少個
10 count_HW = 0
11 count_99HW = 0
12 for i in m_L:
13     # 判斷i是否是回文數
14     s = str(i)  # 將整型數據轉換為字符類型
15     if s == s[::-1]:
16         count_HW += 1
17         print("s:", s)
18         if s.find('99') != -1:  # 在回文數中找是否存在99這個數字
19             count_99HW += 1
20 # 3.顯示結果:
21 print("{}位的數字列表中回文數是{}個,包含'99‘的有{}個".format(m, count_HW, count_99HW))
View Code

 

  •  折半查找

 1 # 折半查找
 2 # L=[34,57,68,78,78,101,106],N=45or57,返回57所在的索引號
 3 
 4 # L_index=[0,1,2,3,4,5,6]
 5 # 1.數據准備
 6 import random
 7 
 8 L = []
 9 for i in range(0, 10):
10     L.append(random.randint(0, 100))
11 L.sort()
12 print(L)
13 # 2.折半查找
14 max_index = len(L) - 1
15 min_index = 0
16 # 用戶輸入數據
17 N = int(input("請輸入要查找的數據:"))
18 while True:
19     if max_index >= min_index:
20         # 查找
21         # 用戶查找數據
22         i = (max_index + min_index) // 2
23         if N == L[i]:
24             print("找到{0},它的索引號為{1}".format(N, i))
25             break
26         elif N > L[i]:
27             min_index = i + 1
28         else:
29             max_index = i - 1
30     else:
31         # index=-1 #表示沒有找到
32         print("沒有找到{}".format(N))
33         break
View Code

  •  數字金字塔

 1 # 1.用戶數字金字塔的層數
 2 num = eval(input("請輸入一個整數:"))
 3 print(num)
 4 # 2.顯示數字金字塔
 5 # 2.0初始化變量
 6 level = 1
 7 # 2.1 循環輸出N層數字
 8 while level <= num:
 9     # 2.1.1輸出第level層數字,level是從1到N
10     kk = 1  # 表示的每一層開始顯示的時候是第幾個數
11     t = level  # 表示輸出第幾個層
12     length = 2 * t - 1  # 表示每一層的數字的總長度
13     # 顯示第t層的數字
14     while kk <= length:  # 顯示的數字個數
15         if kk == 1:  # 表示第一個數字
16             if kk == length:  # 表示第1層數字也表示最后一個數字
17                 print(format(t, str(2 * num - 1) + "d"), "\n")
18                 break
19             else:  # kk是第一數,但是 不是最后一個的
20                 print(format(t, str(2 * (num - level) + 1) + "d"), '', end=" ")
21                 t = -1  # 要顯示的下一個數
22         else:  # 其他位置的數字的處理
23             if kk == length:
24                 print(t, '\n')
25             elif kk <= length / 2:
26                 print(t, "", end="")
27                 t -= 1
28             else:
29                 print(t, "", end="")
30                 t += 1
31         kk += 1
32     level += 1
View Code

 

  •  猜數字游戲

此題有bug,計數器沒設置好。

 1 import random
 2 
 3 
 4 def GuessNumber():
 5     # 編程,實現猜數字游戲
 6     # 1.產生隨機數
 7     number = random.randint(0, 100)
 8     # 2.猜數字
 9     guess = 0  # 保存猜的次數
10     # 循環猜的過程,退出的循環的條件?猜到了退出,或者猜到6次的時候退出
11     max_Num = 100  # 上限
12     min_Num = 0  # 下限
13     while guess <= 6:
14         # 2.1 用戶輸入猜的數字
15         try:
16             guess_Num = int(input('請輸入您要猜的數字({0}-{1}):'.format(min_Num, max_Num)))
17             # 2.2 判斷猜的數字大小正確三種可能性
18             guess += 1  # 計數加1
19             if guess_Num == number:
20                 print('恭喜您,您猜對了!')
21                 break
22             elif guess_Num > number:
23                 print('您猜大了!您還可以猜{}次!'.format(6 - guess))
24                 max_Num = guess_Num
25             elif guess_Num < number:
26                 print('您猜小了!您還可以猜{}次!'.format(6 - guess))
27                 min_Num = guess_Num
28             else:
29                 print('輸入的數據有誤!您還可以猜{}次!'.format(6 - guess))
30         except Exception as e:
31             print(e)
32 
33 
34 if __name__ == '__main__':
35     GuessNumber()
View Code

 

  •  新年倒計時

1 num = 60
2 # 顯示60,59,...0:顯示數字,數字遞減
3 print('新年到了咱們一起倒數吧!')
4 while num >= 0:
5     # print(num)
6     print('倒計時{}秒'.format(num))
7     num -= 1
8 
9 print('新年快樂!')
View Code

 

 

 

  •  數字連加和連乘

1 # 1.創建1~10的自然數列表
2 sum_L = 0  # 連加初始為0
3 mul_L = 1  # 連乘初始為0
4 for i in range(1, 11):
5     sum_L += i
6     mul_L *= i
7 # 2.輸出結果
8 print('1-10連加的結果是{},連乘的結果是{}'.format(sum_L, mul_L))
View Code

  •  九九乘法表

1 #九九乘法表
2 for x in range(1,10):
3     for y in range(1,x+1):
4         print(f'{x}*{y}={x*y}',end='\t')
5     print('\r')

 

  •  成績判斷

 1 # 判斷成績為優秀、良好和不及格
 2 print("----成績判斷----")
 3 # 1.用戶輸入數據:
 4 while True:
 5     score = float(input("請輸入您的成績:"))
 6     # 2.if ..elif..else判斷
 7     if score >= 90:
 8         print("您的成績是%.2f,經鑒定,為A級!\n" % score)
 9 
10     elif score >= 80 and score < 90:
11         print("您的成績是%.2f,經鑒定,為B級!\n" % score)
12     elif score >= 70 and score < 80:
13         print("您的成績是%.2f,經鑒定,為C級!\n" % score)
14     elif score >= 60 and score < 70:
15         print("您的成績是%.2f,經鑒定,為D級!\n" % score)
16     else:
17         print("您的成績是%.2f,經鑒定,為不及格的E級!請再接再厲!\n" % score)
18         break
View Code

 

  •  1-100的和

1 # 計算1~100之間所有整數的和
2 sum = 0
3 for i in range(1, 101):
4     sum += i
5     # sum = sum + i 等同於上面的寫法
6 print(sum)
View Code

5.函數

  • 全局變量與局部變量

 1 '''
 2 總結:
 3  1.全局變量如果要在函數中被引用,則需要使用global對其進行聲明,並且沒有同名的局部變量
 4  2.局部變量只能在函數中被引用,函數外不可見
 5  3.局部變量和全局變量同名,函數是無法引用全局變量
 6 '''
 7 sum1 = 0
 8 
 9 
10 def sum_x(x):  # 函數
11     # sum1=0 #局部變量
12     sum1 = 2  # 如果局部變量和全局變量名字一致,會出錯,用global聲明全局變量
13     # global sum1  #說明sum1是一個全局變量
14     print("sum1=", sum1)
15     for i in x:
16         sum1 += i
17     return sum1
18 
19 
20 print(sum_x([2, 4]), "sum1=", sum1)
View Code

  • 自定義函數並導入

 1 # steak.py
 2 def make_steak(d, *other):
 3     print("Make a steak well done in %d" % d + "with the other:")
 4     for o in other:
 5         print("-" + o)
 6 
 7 
 8 def pay(money):
 9     balance = 100
10     return balance
steak.py
1 #CollApp.py
2 from steak import *
3 
4 make_steak(8, "red mine")
5 print("卡里的余額是:", pay(120))

  •  數值運算

 1 def add(x, y):  # def函數定義關鍵字,add函數名稱,x,y參數
 2     return x + y  # 返回表達式的計算結果
 3 
 4 
 5 def sum_L(x_L):  # 求和
 6     total = 0
 7     for i in x_L:
 8         total += i
 9     # 對列表x_L求和,結果保存在total
10     return total
11 
12 
13 def ave_L(x_L):  # 求均值
14     total = 0
15     for i in x_L:
16         total += i
17     return total / len(x_L)
18 
19 
20 def sum_2L(x_L):  # 求平方和
21     total = 0
22     for i in x_L:
23         total += i ** 2
24     return total
25 
26 
27 if __name__ == '__main__':  # 把運行的語句放到main函數中,否則其他文件代碼用此文件的函數用完后,還會繼續往下執行!
28     result1 = add(3, 4)  # 調用函數add進行兩個數的加法運算
29     print(result1)
30     result2 = sum_L([1, 2, 3])
31     result3 = ave_L([1, 2, 3])
32     result4 = sum_2L([1, 2, 3])
33     print("[1, 2, 3]:\n總和為:{}\n均值為:{}\n平方和為:{}".format(result2, result3, result4))
Mydef.py

 1 from ch05.Demo.MyDef import ave_L as al
 2 
 3 
 4 # 定義求方差的函數,並調用該函數完成方差求解
 5 # 調用函數求給定的任意數的方差(可變數量的參數調用)
 6 
 7 def fc(*args):  # 可變參數args獲取的是元組類型
 8     m = len(args)  # 元組的長度
 9     ave = al(args)
10     total = 0
11     for i in args:
12         total += (i - ave) ** 2
13     return total / m
14 
15 
16 print(fc(1, 2, 3))
fangcha.py

 

 1 from ch05.Demo.MyDef import ave_L as al  # 取別名為al
 2 
 3 
 4 # 定義函數求輸入學生的平均成績,並顯示每個科目的成績
 5 
 6 
 7 def ave_Student(**kwargs):
 8     value = list(kwargs.values())  # 獲得成績的數據
 9     ave_value = al(value)  # 調用自定義函數ave_L求平均值
10     return ave_value
11     # return ave_L(value)
12 
13 
14 result = ave_Student(Java=98, math=99, english=100)
15 print(result)
studentScore.py

  • map函數

1 # map(function,list):參數,返回結果:map對象
2 def add(x, y):
3     return x ** 2 + y ** 2
4 
5 
6 print(list(map(add, [3, 4], [3, 4])))
View Code

 

1 def add(x):
2     return x**3
3 numbers = list(range(1,20,2))
4 # num1 = list(map(add,numbers))
5 num2 = list(map(lambda x:x+3,numbers))
6 print(numbers)
7 # print(num1)
8 print(num2)
View Code

  •  過濾出1-100中平方根是整數的數

 1 import math
 2 
 3 
 4 # filter
 5 # 過濾出1-100中平方根是整數的數
 6 
 7 def is_sqr(x):
 8     return math.sqrt(x) % 1 == 0
 9 
10 
11 newlist = filter(is_sqr, range(1, 101))
12 print(list(newlist))
13 
14 # lambda
15 numbers = list(range(1, 101))
16 newlist2 = list(filter(lambda x: math.sqrt(x) % 1 == 0, numbers))#
17 
18 print(newlist2)
View Code

  •  漢諾塔

 1 def hlt(n,a,b,c):
 2     if n ==1:
 3         print("{}->{}".format(a,c))
 4 
 5     elif n>1:
 6         hlt(n-1,a,b,c)
 7         print("{}->{}".format(a,c))
 8         hlt(n-1,b,a,c)
 9 
10 hlt(3,"A塔","B塔","C塔")
View Code

 

  •  函數遞歸

 1 # 遞歸函數:特性:1.具有相似性,fib(10)和計算fib(9) 2.解決問題,規模在縮減,最后能夠返回具體的數
 2 # 斐波那契數列
 3 def fib(n):
 4     if n == 1:
 5         return 0
 6     elif n == 2:
 7         return 1
 8     elif n > 2:
 9         return fib(n - 1) + fib(n - 2)  # 在函數中調用函數本身,遞歸
10     else:
11         print("輸入的數據有誤!")
12 
13 
14 print(fib(3))
15 
16 
17 # 求階乘
18 def mul(n):  # mul返回n的階乘
19     if n == 0:
20         return 1
21     elif n > 0:
22         return n * mul(n - 1)  # n!=n*(n-1)! 即:1x2x3...x(n-1)*n
23     else:
24         return -1  # 若輸入有誤,返回-1
25 
26 
27 print(mul(5))
28 
29 
30 def sum(n):
31     if n == 0:
32         return 0
33     if n >= 1 and n <= 100:
34         return n + sum(n - 1)
35     else:
36         print("輸入的數據超出了范圍!")
37 
38 
39 print(sum(5))
View Code

 

  •  漢諾塔問題

 1 i = 1
 2 
 3 
 4 def move(n, mfrom, mto):
 5     global i
 6     print("第%d步:將%d號盤子從%s -> %s" % (i, n, mfrom, mto))
 7     i += 1
 8 
 9 
10 def hanoi(n, A, B, C):
11     if n == 1:
12         move(1, A, C)
13     else:
14         hanoi(n - 1, A, C, B)
15         move(n, A, C)
16         hanoi(n - 1, B, A, C)
17 
18 
19 print("移動步驟如下:")
20 hanoi(3, 'A', 'B', 'C')
View Code

 

  •  定義一個求列表中位數的函數

 1 # 構建一個計算列表中位數的函數
 2 
 3 def median(*args):
 4     data = sorted(*args)
 5     data_len = len(data)
 6     print("排序后的列表為:", data)
 7     if (data_len % 2 == 0):
 8         result = (data[int(data_len / 2)] + data[int(data_len / 2 - 1)]) / 2
 9         print("該列表有{0}個數字,長度是偶數,中位數為{1}".format(int(data_len), result))
10     else:
11         result = data[int(data_len / 2)]
12         print("該列表有{0}個數字,長度是奇數,中位數為{1}".format(int(data_len), result))
13 
14 
15 median([2, 1, 6, 4, 10, 8, 9, 10])
16 print("\n")
17 median([2, 1, 6, 4, 10, 8, 9, 10, 25, 80, 8])
View Code

6.面向對象編程

  • Car類

 1 # Car.py
 2 class Car:
 3     wheelNum = 4
 4     color = 'red'
 5 
 6     def getCarInfo(self, name):
 7         self.name = name
 8         print(self.name, '有%d個車輪,顏色是%s' % (self.wheelNum, self.color))
 9 
10     def run(self):
11         print("車行駛在學習的大道上")
12 
13     def hideself(self):
14         print("現在隱身")
15 
16 
17 car1 = Car()
18 car1.getCarInfo('Land Rover')
19 car1.run()
20 car1.hideself()
View Code

  •  Cat類

 1 # 類成員變量:訪問類成員變量:類名.變量名   #訪問實例成員變量:self.成員變量名
 2 class Cat():
 3     name = ""  # 類成員變量
 4     age = 3
 5 
 6     def __init__(self):
 7         self.name = "kitty"
 8 
 9     def __init__(self, name, age):  # 構造方法,初始化數據 # 局部變量
10         self.__name = name  # 實例對象的成員變量
11         self.__age = age  # 利用__將實例變量私有化
12 
13     def __getName(self):  # 私有方法不能在類定義之外的地方被調用
14         return self.name
15 
16     # def __del__(self):  # 刪除
17     #     print("析構方法被調用")
18 
19     def sleep(self):  # self當前對象,this
20         print("%d歲的%s正在陽台睡覺" % (self.__age, self.__name))
21 
22     def eat(self, food):
23         self.food = food  # food 局部變量,self.food成員變量  this.name=name
24         print("%d歲的%s正在吃%s" % (self.__age, self.__name, self.food))
25 
26 
27 cat1 = Cat("嘟嘟", 2)
28 cat1.sleep()
29 cat1.eat("fish")
30 
31 cat2 = Cat("土豆", 5)
32 cat2.name = "小王"
33 cat2.eat("rice")
34 del cat2
35 # cat2.eat("rice") NameError: name 'cat2' is not defined
36 print(Cat.name)
View Code

 

 1 # 類成員變量:訪問類成員變量:類名.變量名   #訪問實例成員變量:self.成員變量名
 2 class Cat():
 3     name = "kitty"  # 類成員變量
 4     age = 3
 5 
 6     def __init__(self, name, age):  # 構造方法,初始化數據 # 局部變量
 7         self.name = name  # 實例對象的成員變量
 8         self.age = age
 9         self.info = [self.name, self.age]
10         self.index = -1
11 
12     def __iter__(self):
13         print("名字 年齡")
14         return self
15 
16     def next(self):  # 取出屬性
17         if self.index == len(self.info) - 1:
18             raise StopIteration
19         self.index += 1
20         return self.info[self.index]
21 
22     def __del__(self):  # 刪除
23         print("析構方法被調用")
24 
25     def sleep(self):  # self當前對象,this
26         print("%d歲的%s正在陽台睡覺" % (self.age, self.name))
27 
28     def eat(self, food):
29         self.food = food  # food 局部變量,self.food成員變量  this.name=name
30         print("%d歲的%s正在吃%s" % (self.age, self.name, self.food))
31 
32 
33 cat1 = Cat("嘟嘟", 2)
34 cat1.sleep()
35 itor = iter(cat1.next, 1)
36 for info in itor:
37     print(info)
View Code

 

 

 

  •  繼承

 1 class Cat():  #
 2     def __init__(self):
 3         self.name = ''
 4         self.age = 4
 5         self.info = [self.name, self.age]
 6         self.index = -1
 7 
 8     def run(self):
 9         print(self.name, "--在跑")
10 
11     def getName(self):
12         return self.name
13 
14     def getAge(self):
15         return self.age
16 
17     def __iter__(self):
18         print("名字 年齡")
19         return self
20 
21     def next(self):
22         if self.index == len(self.info) - 1:
23             raise StopIteration
24         self.index += 1
25         return self.info[self.index]
26 
27 
28 class Bosi(Cat):
29     def setName(self, newName):
30         self.name = newName
31 
32     def eat(self):
33         print(self.name, '--在吃')
34 
35 
36 bs = Bosi()
37 print("bs的名字為:", bs.name)
38 print("bs的年齡為:", bs.age)
39 bs.run()
40 
41 bs.setName("波斯貓")
42 bs.eat()
43 
44 interator = iter(bs.next, 1)
45 
46 for info in interator:
47     print(info)
View Code

7.文件基礎

  • 列表求和

1 file_name = "../data/score.txt"
2 with open(file_name, mode="r", encoding="utf-8") as f:
3     text = f.read()
4     text_L = [float(x) for x in text.split("\n")]  # 以\n為分隔,遍歷出text中的數據
5     print(text_L, type(text_L))
6     print(text_L, sum(text_L))
View Code

 

1 file_name = "../data/score.txt"
2 with open(file_name, mode="r", encoding="utf-8") as f:
3     text = f.readlines()
4     print(text, type(text))  # readlines:按行讀所有, 讀出來的直接就是list
5     text_L = [float(x.rstrip()) for x in text]  # 遍歷出text中的數據保存在x中,並用rstrip去掉末尾字符,最后轉換為float型
6     print(text_L)
7     print(sum(text_L))
View Code

 

 

 

readline

1 file_name = "../data/score.txt"
2 with open(file_name, mode="r", encoding="utf-8") as f:
3     text = f.readline()
4     print(text, type(text))

 

 

  •  讀寫文件

 1 file_name = "../data/score.txt"
 2 with open(file_name, mode="r", encoding="utf-8") as f:
 3     text = f.read()
 4     text_L = [float(x) for x in text.split("\n")]  # 以\n為分隔,遍歷出text中的數據
 5     print(text_L, type(text_L))
 6     Sum=sum(text_L)
 7     print("數據是:{},累加結果是:{}".format(text_L, Sum))
 8 
 9 with open(file_name, mode="a", encoding="utf-8") as f:
10     f.write("\n總共是:{}".format(Sum))
11     print("寫入成功!")
12     f.close()
View Code

 1 try:
 2     f = open("../data/Student.txt", mode="r")
 3     txt = f.read()
 4     f.close()
 5 except:
 6     print("找不到文件!")
 7 else:
 8     print(txt, type(txt))
 9 # finally:
10 #     if f:
11 #         f.close()
12 
13 print("\n")
14 
15 try:
16     with open("../data/Student.txt", mode="r") as f:
17         print(f.read())
18 except:
19     print("找不到文件!")
View Code

 

 

 

 

1 try:
2     with open("../data/Singer.txt", mode="r", encoding="utf-8")as f:
3         text = f.read()
4         # print(text)
5         print("”音樂“在新聞片段中出現的次數:", text.count("音樂"))
6 except:
7     print("找不到文件!")
View Code

 

 

 

 1 try:
 2     f = open("../data/e_ point.txt", "r")
 3     print(f.read())
 4 finally:
 5     if f:
 6         f.close()
 7 
 8 print("\n")
 9 
10 with open("../data/e_ point.txt", "r") as f:
11     print(f.read())
12     f.close()
View Code

 

 

 

1 file_name = '../data/e_ point.txt'
2 with open(file_name, "r")as f:
3     for line_t in f:
4         print(line_t)

 

 

 

去掉換行符:

1 file_name = "../data/e_ point.txt"
2 with open(file_name, "r") as f:
3     for line_t in f:
4         print(line_t.rstrip())

 

 

 

read 返回字符串

1 with open("../data/e_ point.txt") as f:
2     txts = f.read()
3 print(type(txts))
4 
5 print(txts)

 

 

 

 readlines 返回列表:

1 with open("../data/e_ point.txt") as f:
2     txts = f.readlines()
3 print(type(txts))
4 print(txts)

 

 

 

readlines讀取后,遍歷並去除換行符輸出

1 with open("../data/e_ point.txt") as f:
2     txts=f.readlines()
3 for txt in txts:
4     print(txt.strip())

 

 

 

readline 返回字符串

1 with open("../data/e_ point.txt")as f:
2     txt = f.readline()
3 print(type(txt))
4 print(txt)

 

 

 

1 file_name = "../data/words.txt"
2 f = open(file_name, "w")
3 f.write("Hello,world!")
4 f.close()

 

1 file_name = "../data/data.txt"
2 f = open(file_name, "w")
3 data = list(range(1, 11))
4 # f.write(data)  #TypeError: write() argument must be str, not list
5 f.write(str(data))
6 f.close()
View Code

 

 

**:以下words.txt 每次運行完,自己手動刪除了所有數據后,再測試。

1 file_name = "../data/words.txt"
2 f = open(file_name, "w")
3 f.write("Hello,world!\n")
4 f.write("I love Python!\n")
5 f.close()

 

 

 

1 file_name = "../data/words.txt"
2 with open(file_name, "w",encoding="gbk")as f:
3     f.write("Hello,world!\n")
4     f.write("I love Python!\n")

 

 

 

1 file_name = "../data/words.txt"
2 with open(file_name, "a")as f:
3     f.write("What's your favourite language?\n")
4     f.write("My favourite language is Python!\n")

 

 

  •  讀寫CSV文件

csv.reader()

csv.Dictreader()

鳶尾花數據集

 1 import csv
 2 
 3 file_name = "../data/iris.csv"  # csv是文本文件
 4 with open(file_name, "r") as f:
 5     reader = csv.reader(f)
 6     # print(reader,type(reader))
 7     # #直接打印reader:<_csv.reader object at 0x000001E8AF492520>  類型: <class '_csv.reader'> 是一個reader對象
 8     iris = [iris_item for iris_item in reader]
 9 print(iris)
10 print(type(iris))
View Code

 

 

 

1 import csv
2 
3 file_name = "../data/iris.csv"
4 with open(file_name, "r") as f:
5     reader = csv.DictReader(f)
6     # print(reader,type(reader)) # <csv.DictReader object at 0x000001CBAA89F0A0> <class 'csv.DictReader'>
7     iris = [iris_item for iris_item in reader]
8 print(iris)
View Code

1 import csv
2 
3 file_name = "../data/iris.csv"
4 with open(file_name, "r") as f:
5     reader = csv.DictReader(f)
6     column = [iris_item["Sepal.Length"] for iris_item in reader]
7 print(column)
View Code

 

 

 

  •  寫

 1 import csv
 2 
 3 file_name = "../data/iris.csv"  # csv是文本文件
 4 with open(file_name, "r") as f:
 5     reader = csv.reader(f)
 6     # print(reader,type(reader))
 7     # #直接打印reader:<_csv.reader object at 0x000001E8AF492520>  類型: <class '_csv.reader'> 是一個reader對象
 8     iris = [iris_item for iris_item in reader]
 9 
10 file_name = "../data/test.csv"
11 
12 with open(file_name, "w", newline='')as f:
13     write_csv = csv.writer(f)
14     write_csv.writerow(iris)
View Code

 

 

 1 import csv
 2 
 3 file_name = "../data/iris.csv"
 4 with open(file_name, "r") as f:
 5     reader = csv.DictReader(f)
 6     iris = [iris_item for iris_item in reader]
 7 
 8 file_name2 = "../data/test2.csv"
 9 my_key = []  # 鍵的集合
10 for i in iris[0].keys():
11     my_key.append(i)
12 
13 with open(file_name2, "w", newline='')as f:
14     write_csv = csv.DictWriter(f, my_key)
15     write_csv.writeheader()  # 輸入標題
16     write_csv.writerows(iris)  # 輸入數據
View Code

 

 

 

  •  將1-100的平方和寫入文件

1 squares = [value ** 2 for value in range(1, 101)]
2 import csv
3 
4 file_name = "../data/squares.csv"
5 with open(file_name, "w", newline='')as f:
6     write_csv = csv.writer(f)
7     for square in squares:
8         write_csv.writerows([str(square)])
View Code

 

 

  •  讀取學生成績,求平均成績

 

 1 import csv
 2 
 3 # 構建學生成績的csv文件,從文件中讀取數據,顯示學號為2
 4 file_name = "../data/學生成績.csv"  # csv是文本文件
 5 N = "2"  # 學號是2
 6 with open(file_name, "r") as f:
 7     reader = csv.reader(f)
 8     score = [scores_item for scores_item in reader]
 9     for i in score:
10         if i[0] == N:
11             print(i)
12             print("學號為:", i[0])
13             break
14     else:
15         print("{}學號不存在".format(N))
16 
17     python_l = [float(score[i][2]) for i in range(1, len(score))]  # 索引1到索引3有成績數據,索引0是標題,所以從索引1開始
18     # score[i][2] 是成績
19     python_ave = sum(python_l) / len(python_l)
20     print("平均成績是:{}".format(python_ave))
21 print(score)
22 # [['學號', '姓名', 'Python'], ['1', 'henry', '87'], ['2', 'David', '98'], ['3', 'Alice', '67']]
View Code

 

 

 

只算Python鍵的值的平均值:

 1 import csv
 2 
 3 # DictReader 保存字典形式
 4 file_name = "../data/學生成績.csv"
 5 N = "2"  # 學號是2
 6 with open(file_name, "r") as f:
 7     reader = csv.DictReader(f)
 8     datas = [float(datas_item["Python"]) for datas_item in reader]
 9     # print(datas) # python 中這個列的成績數據:['87','98','67']
10     print(sum(datas) / len(datas))
View Code

 

csv.reader()讀取;csv.writer()寫入

 1 import csv
 2 
 3 filename = "../data/學生成績.csv"
 4 with open(filename, "r")as f:
 5     reader = csv.reader(f)
 6     datas = [datas_item for datas_item in reader]
 7     print(datas)
 8 
 9 # 寫文件
10 filename_w = "../data/學生成績副本.csv"
11 with open(filename_w, "w") as f:
12     writer_csv = csv.writer(f)
13     writer_csv.writerows(datas)
View Code

 

csv.DictReader()讀取;csv.DictWriter()寫入

 1 import csv
 2 
 3 filename = "../data/學生成績.csv"
 4 with open(filename, "r") as f:
 5     reader = csv.DictReader(f)
 6     datasL = [datas_item for datas_item in reader]
 7     print(datasL)
 8 mykeys = [i for i in datasL[0].keys()]
 9 
10 # 寫文件方法二:
11 filename_w = "../data/成績信息副本.csv"
12 with open(filename_w, "w", newline='') as f:
13     writer_csv = csv.DictWriter(f, mykeys)
14     writer_csv.writeheader()
15     writer_csv.writerows(datasL)
View Code


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM