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-2025 CODEPRJ.COM