Python课程课后作业

因为之后可能会换电脑,所以在这里记录一下Python课程的课后答案以作备份。

实验二

01

1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*-

length = float(input('请输入长方形的长:'))
width = float(input('请输入长方形的宽:'))
height = float(input('请输入长方形的高:'))

print('长方形的体积为:', length*width*height)
print('长方形的表面积为:', 2*(length*width+length*height+width*height))

02

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-

import math
x = float(input('请输入x的值:'))
y = float(input('请输入y的值:'))
z = float(input('请输入z的值:'))
numerator = (3*x)+4*((x**2+2*(y**2))**0.5) # 分子
denominator = 1+math.cos(z**3) # 分母
print('最终结果为:', numerator/denominator)

03

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-

import math


delter = 4**2 - 4*1*3
x1 = (-4+math.sqrt(delter))/2*1
x2 = (-4-math.sqrt(delter))/2*1
print(f'x1={x1},x2={x2}')

04

1
2
3
4
5
6
# -*- coding: utf-8 -*-

str = '君子之行,修以养身,俭以养德,非淡泊无以明志,非宁静无以致远'
print(str)
print(str[13])
print(str[15:]) # 切片,从‘非’开始,一直切到字符串末尾

05

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: utf-8 -*-

while 1:
a = int(input('请输入要传递的四位数字:'))
if a > 9999 or a < 1000:
print('输入的数字不合法!请重新输入!')
continue
else:
s = str(a) # 先将数字转换成字符串,方便各个位数的提取
# num1,2,3,4分别为千位数,百位数,十位数,个位数
num1 = int(s[0])
num2 = int(s[1])
num3 = int(s[2])
num4 = int(s[3])
num1_new = (num1+5) % 10
num2_new = (num2+5) % 10
num3_new = (num3+5) % 10
num4_new = (num4+5) % 10
print('加密后的数字为:', num1_new*1000+num2_new*100+num3_new*10+num4_new)
break

06

1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding: utf-8 -*-

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst1 = lst[0::2] # 切片,从1开始,每两个切一次
lst2 = lst[1::2] # 切片,从2开始,每两个切一次
print(lst1)
print(lst2)
lst3 = []
for i in range(0, len(lst1)):
el = lst1[i]*10 + lst2[i]
lst3.append(el)

print(lst3)

07

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-

a = float(input('请输入a的值:'))
b = float(input('请输入b的值:'))
c = float(input('请输入c的值:'))
d = float(input('请输入d的值:'))

f = (a+b)*c/d
print(f)

实验三

01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: utf-8 -*-

a = float(input('请输入a的值:'))
b = float(input('请输入b的值:'))
c = float(input('请输入c的值:'))

max_num = max(a, b, c)
min_num = min(a, b, c)
center_num = a

if b == c:
center_num = b

if min_num < b < max_num:
center_num = b

if min_num < c < max_num:
center_num = c

print('这三个数从大到小的顺序为:', max_num, center_num, min_num)

02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- coding: utf-8 -*-

while 1:
a = int(input('请输入一个不多于5位的正整数:'))
if a > 99999 or a < 0:
print('输入的数字不合法!请重新输入!')
continue
else:
s = str(a) # 现将数字转换成字符串
print('该正整数的位数为:', len(s))
s_new = ''
for i in range(1, len(s)+1):
s_new = s_new + s[-i] # i从1开始计数,因为从倒数第1个开始
print('逆序输出如下:', s_new)
break

03

1
2
3
4
5
6
7
# -*- coding: utf-8 -*-

sum_num = 0
for i in range(1, 101):
if i % 4 == 0:
sum_num = sum_num + i
print('1-100范围内能被4整除的所有数的和为:', sum_num)

04

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# -*- coding: utf-8 -*-


# 函数功能:判断素数,是素数返回1,反之返回0
def is_prime(num):
for i in range(2, num): # 从2到该数字前一个数
if num % i == 0: # 不是素数
return 0
return 1


print('100-1000之间的所有素数如下:')
for i in range(100, 1001):
flag = is_prime(i)
if flag == 1:
print(i)

05

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-

count = 0
# a,b,c分别为、百位、十位、个位
for a in range(1, 5):
for b in range(1, 5):
for c in range(1, 5):
if a != b and a != c and b != c: # 各个位数不能相同
print(a*100+b*10+c)
count = count + 1

print(f'能组成{count}个数')

06

1
2
3
4
5
6
7
8
9
10
# -*- coding: utf-8 -*-

print('所有水仙数如下:')
for i in range(100, 1000):
s = str(i)
num_1 = int(s[0])
num_2 = int(s[1])
num_3 = int(s[2])
if num_1**3+num_2**3+num_3**3 == i:
print(i)

07

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: utf-8 -*-

year = int(input('请输入年份:'))
month = int(input('请输入月份:'))

if (year % 4 == 0 and year % 100 !=0) or year % 400 == 0: # 闰年
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
print(f'{year}{month}月有31天')
elif month == 4 or month == 6 or month == 9 or month == 11:
print(f'{year}{month}月有30天')
elif month == 2:
print(f'{year}{month}月有29天')

else: # 非闰年
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
print(f'{year}{month}月有31天')
elif month == 4 or month == 6 or month == 9 or month == 11:
print(f'{year}{month}月有30天')
elif month == 2:
print(f'{year}{month}月有28天')

08

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-

print(' * '.center(21, ' '))
print((' * '*3).center(21, ' '))
print((' * '*5).center(21, ' '))
print((' * '*7).center(21, ' '))
print((' * '*5).center(21, ' '))
print((' * '*3).center(21, ' '))
print(' * '.center(21, ' '))

09

1
2
3
4
5
6
7
8
9
10
# -*- coding: utf-8 -*-

people_num = 13
year = 0
while 1:
year = year + 1
people_num = people_num*1.008
if people_num > 20:
print(f'{year}年后我国人数超过20亿人')
break

10

1
2
3
4
5
6
7
# -*- coding: utf-8 -*-

a = 100000
b = 0.01
a_new = a * 30
b_new = 0.01*(2**30 - 1)
print(f'一个月后陌生人给富翁{a_new}元,富翁给陌生人{b_new}元')

实验四

01

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-

lst1 = [1, 2, 'hello']
lst2 = [3, 4, 'world']

# 方法1,直接相加
lst3 = lst1 + lst2
print(lst3)

# 方法2,extend方法
lst1.extend(lst2)
print(lst1)

02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- coding: utf-8 -*-

import random

lst = []
for i in range(0, 10):
lst.append(random.randint(1, 100)) # 实现符合条件的列表的生成
print(lst)

for i in range(0, len(lst)):
if lst[i]%2 == 1:
lst[i] = lst[i]**2
else:
lst[i] = lst[i]**3
print(lst)

03

1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding: utf-8 -*-

lst = [3, 8, 11, 26, 47]
a = int(input('请输入一个新元素:'))
count = len(lst) # 将count初始化为列表长度
for i in range(0, len(lst)):
if a < lst[i]:
count = i
break

# count即为要插入的索引
lst.insert(count, a)
print(lst)

04

1
2
3
4
5
6
7
# -*- coding: utf-8 -*-

lst = ['jay', 'java', 'jj', 'java', 'jj', 'jj']
# 利用集合来去重复
s_new = set(lst)
lst_new = list(s_new)
print(lst_new)

05

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- coding: utf-8 -*-

import random
t = ()
lst = []
for i in range(0, 20):
lst.append(random.randint(1, 10))
t = tuple(lst) # 由于元组不能进行增删改操作,所以借助列表lst来创造一个元组
print("该元组为:", t)
print("1在元组中出现的次数为:", t.count(1))
print("2在元组中出现的次数为:", t.count(2))
print("3在元组中出现的次数为:", t.count(3))
print("4在元组中出现的次数为:", t.count(4))
print("5在元组中出现的次数为:", t.count(5))
print("6在元组中出现的次数为:", t.count(6))
print("7在元组中出现的次数为:", t.count(7))
print("8在元组中出现的次数为:", t.count(8))
print("9在元组中出现的次数为:", t.count(9))
print("10在元组中出现的次数为:", t.count(10))

06

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-

grade = (68, 87, 83, 91, 93, 79, 68, 86, 66, 78)
print("grade中的第二个元素为:", grade[1])
print("grade中的第3-7个元素为:", grade[2:7])
print("grade是否包含成绩87:", 87 in grade)
print("成绩为78的学生学号为:", grade.index(78) + 1)
print("成绩68在grade中出现的次数为:", grade.count(68))
print("grade中的元素个数为:", len(grade))

07

1
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-

set1 = {2, 5, 9, 1, 3}
set2 = {3, 6, 8, 2, 5}
set1.add(7)
print("set1添加一个新元素7后为:", set1)
print("set2为:", set2)
print("set1和set2的并集为:", set1 | set2)
print("set1和set2的交集为:", set1 & set2)
print("set1和set2的差集为:", set1 - set2)
print("4是否在set1或set2中:", 4 in set1 | set2)

08

1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*-

pay = []
pay.append(float(input("请输入小明早餐费用:")))
pay.append(float(input("请输入小明中餐费用:")))
pay.append(float(input("请输入小明晚餐费用:")))
pay.append(float(input("请输入小明其他费用:")))
print("总费用值为:", sum(pay))

09

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# -*- coding: utf-8 -*-

score = {
'1001': 78,
'1002': 87,
'1003': 90,
'1004': 61,
'1005': 59,
}
# 添加
score['1006'] = 92
print(score)
# 修改
score['1005'] = 60
print(score)
# 删除
score.pop('1001')
print(score)
# 查询学号为1002的学生成绩
lst = list(score.values()) # 将成绩提取到列表中
print("学生成绩的最高分为:", max(lst))
print("学生成绩的最低分为:", min(lst))
print("学生成绩的平均分为:", sum(lst)/len(lst))

实验五

01

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-


def func(n):
return bin(n)


num = int(input("请输入一个十进制整数:"))
print(f"{num}的二进制数为:{func(num)}")

02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# -*- coding: utf-8 -*-


def fibonacci(i): # 函数功能:计算并返回斐波那契数列的第i项
if i == 1 or i == 2:
num = 1
else:
num = fibonacci(i-2) + fibonacci(i-1)
return num


def fibonacci_sum(): # 函数功能:计算并返回斐波那契数列前10项和
sum = 0
for i in range(1, 11):
sum = sum + fibonacci(i)
return sum


for i in range(1, 11):
print(f"斐波那契数列的第{i}项是:", fibonacci(i))
print()
print("斐波那契数列前10项和是:", fibonacci_sum())

03

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# -*- coding: utf-8 -*-


def func(str = ''): # 现将str定义为字符串
number_num = 0
letter_num = 0
else_num = 0
for item in str: # 字符串也是可迭代的
if item.isdigit(): # item是数字
number_num = number_num + 1
elif item.isalpha(): # item是字母
letter_num = letter_num + 1
else:
else_num = else_num + 1
return number_num, letter_num, else_num # 以元组形式返回


str = input("请输入一个字符串:")
t = func(str)
print("字符串中数字个数为:", t[0])
print("字符串中字母个数为:", t[1])
print("字符串中其他字符类型个数为:", t[2])

04

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-


def func(str1='', str2=''):
lst = str1.split(str2) # 先切割成列表
str3 = ''.join(lst) # 再利用join函数拼接起来
return str3


s1 = input('请输入str1:')
s2 = input('请输入str2:')
print('结果为:', func(s1, s2))

05

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# -*- coding: utf-8 -*-


def func(n):
sum = 0
if n % 2 == 0:
for i in range(1, n+1):
sum = sum + 1/(2*i)
if n % 2 == 1:
for i in range(1, n+2):
sum = sum + 1/(2*i - 1)
return sum


n = int(input('请输入n的值:'))
print('sum = ', func(n))

06

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# -*- coding: utf-8 -*-


# 非递归函数
def fun():
age = 10
for i in range(0, 4):
age = age + 2
return age


# 递归函数
def func(i):
if i == 1:
age = 10
else:
age = 2 + func(i-1)
return age


print('第5个人的岁数是(非递归函数):', fun())
print('第5个人的岁数是(递归函数):', func(5))

07

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding: utf-8 -*-


def isWs(n):
lst = [] # 用于存放n的所有因子(不含n)的列表
for i in range(1, n):
if n % i == 0:
lst.append(i)
sum_i = sum(lst)
if sum_i == n:
return True
elif sum_i != n:
return False


num = int(input("请输入一个正整数:"))
print(f"{num}是否为完数:", isWs(num))

08

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
# -*- coding: utf-8 -*-

import math


def is_prime(n): # 函数功能:判断n是否为素数(0表示非素数,1表示素数)
if n < 2:
return 0
else:
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return 0
return 1


def isGDBH(n):
lst = [] # 用于存放结果
for num1 in range(2, int(n/2) + 1):
num2 = n - num1
if is_prime(num1) == 1 and is_prime(num2) == 1: # num1和num2都是素数
lst.append(f"{num1} + {num2} = {n}")
return lst


while 1:
n = int(input("请输入一个大于2的偶数:"))
if n > 2 and n % 2 == 0:
print(isGDBH(n))
break
else:
print("输入数字不合法!请重新输入")

09

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
import math


def deco(func):
def inner(*args):
for i in args:
if i < 0:
return print('参数不合法!')
return func(*args)
return inner


@deco
def triangle(a, b, c):
return a + b + c


@deco
def rectangle(a, b):
return (a + b) * 2


@deco
def cicle(r):
return math.pi * 2 * r


if __name__ == "__main__":
r = int(input('请输入圆的半径:'))
print(cicle(r))
print(triangle(1,2,-3))
print(rectangle(1,2))

实验六

01

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
55
56
57
58
59
# -*- coding: utf-8 -*-

import abc


class Shape(metaclass=abc.ABCMeta):
@abc.abstractmethod
def getArea(self):
pass

@abc.abstractmethod
def getPerimeter(self):
pass


class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c

def getArea(self):
return self.a+self.b+self.c

def getPerimeter(self):
p = (self.a+self.b+self.c)/2
s = (p*(p-self.a)*(p-self.b)*(p-self.c))**0.5
return s


class Rectangle(Shape):
def __init__(self, a, b):
self.a = a
self.b = b

def getArea(self):
return (self.a+self.b)*2

def getPerimeter(self):
return self.a*self.b


class Cricle(Shape):
def __init__(self, r):
self.r = r

def getArea(self):
return 2*3.1415926*self.r

def getPerimeter(self):
return 3.1415926*(self.r**2)


tir = Triangle(3, 4, 5)
rec = Rectangle(2, 3)
cri = Cricle(4)
print(f"三角形的周长为{tir.getArea()},面积为{tir.getPerimeter()}")
print(f"矩形的周长为{rec.getArea()},面积为{rec.getPerimeter()}")
print(f"圆的周长为{cri.getArea()},面积为{cri.getPerimeter()}")

02

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# -*- coding: utf-8 -*-


class Commodity: # 定义商品类
def __init__(self, name, num, in_price, out_price):
self.name = name
self.num = num
self.in_price = in_price # 进货价
self.out_price = out_price # 出售价


class Supermarket:
commodities = [] # 商品列表,每一个元素都是商品类
out_money = 0.0 # 超市进货花销
in_money = 0.0 # 超市售出

def __init__(self):
self.commodities.append(Commodity("O泡果奶", 122, 4, 5))
self.commodities.append(Commodity("辣条", 300, 1, 2.5))
self.commodities.append(Commodity("馒头", 404, 0.5, 1))
self.commodities.append(Commodity("饮料", 233, 3.5, 4))

def menu(self): # 菜单
print("--------超市进销存管理系统--------")
print("1.显示所有商品")
print("2.添加商品")
print("3.修改商品")
print("4.删除商品")
print("5.卖出商品")
print("6.汇总")
print("-1.退出系统")
while(1):
item = int(input("请输入序号:"))
if item == 1:
self.show()
elif item == 2:
self.add()
elif item == 3:
self.alter()
elif item == 4:
self.delete()
elif item == 5:
self.sold()
elif item == 6:
self.summarize()
elif item == -1:
print("感谢使用,退出中。。。")
break
else:
print("输入序号无效!请重新输入:")

def show(self):
for commoditie in self.commodities:
print(f"商品的名称为:{commoditie.name},数量为:{commoditie.num},"
f"进货价格为:{commoditie.in_price}元,出售价格为:{commoditie.out_price}元")

def add(self): # 增加商品
add_name = input("请输入要添加的商品名称:")
add_num = int(input("请输入要添加的商品数量:"))
for item in self.commodities: # 判断进货的商品是否是新商品
if item.name == add_name:
item.num = item.num+add_num
is_new = 0
self.out_money = self.out_money + (add_num * item.in_price)
break
else:
is_new = 1
if is_new == 1:
add_in_price = float(input("请输入要添加的商品进货价格:"))
add_out_price = float(input("请输入要添加的商品出售价格:"))
self.commodities.append(Commodity(add_name, add_num, add_in_price, add_out_price))
self.out_money = self.out_money+(add_num*add_in_price)
print("添加成功!")

def alter(self): # 修改商品
alter_name = input("请输入你要修改的商品原来的名称:")
alter_falg = 0
for item in self.commodities: # 判断要修改的商品是否已经在超市中
if item.name == alter_name:
new_name = input("请输入你要修改的商品名:")
new_num = int(input("请输入你要修改的商品的数量:"))
new_in_price = float(input("请输入你要修改的商品的进货价格:"))
new_out_price = float(input("请输入你要修改的商品的出售价格:"))
item.name = new_name
item.num = new_num
item.in_price = new_in_price
item.out_price = new_out_price
alter_falg = 1
if alter_falg == 0:
print("该商品不在超市中!请及时进货")

def delete(self): # 删除商品
delete_name = input("请输入你要删除的商品原来的名称:")
delete_falg = 0
for item in self.commodities: # 判断要删除的商品是否已经在超市中
if item.name == delete_name:
self.commodities.remove(item)
print("删除成功!")
delete_falg = 1
if delete_falg == 0:
print("该商品不在超市中!无法删除!")

def sold(self): # 出售商品
sold_name = input("请输入要出售的商品名称:")
sold_falg = 0
for item in self.commodities: # 判断要出售的商品是否已经在超市中
if item.name == sold_name:
sold_num = int(input("请输入要出售的数量:"))
if sold_num < item.num: # 要出售的数量小于库存量
item.num = item.num - sold_num
self.in_money = sold_num*item.out_price
print("出售成功!")
else:
print(f"{sold_name}库存不足!")
sold_falg = 1
if sold_falg == 0:
print("该商品不在超市中!请及时进货")

def summarize(self): # 汇总
print(f"目前为止进货一共花了{self.out_money}元!")
print(f"目前为止出售了{self.in_money}元!")


if __name__ == '__main__':
su = Supermarket()
su.menu()

实验七

01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding: utf-8 -*-

import turtle


def main():
count = 1
while count <= 5:

turtle.forward(100) # 向前走50
turtle.right(144) # 向右转144度
count = count + 1
turtle.exitonclick()


if __name__ == '__main__':
main()

02

1
2
3
4
5
6
7
8
9
10
# -*- coding: utf-8 -*-

from datetime import datetime
dt = datetime.now()
print(f"当前时间为:{dt}")
print(f"当前时间的年是:{dt.year}年")
print(f"当前时间的月是:{dt.month}月")
print(f"当前时间的日是:{dt.day}号")
print(f"当前时间是第{dt.isocalendar()[1]}周")
print(f"当天是该周的第{dt.isoweekday()}天")

03

1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*-


import os


print(f"当前项目的工作路径为:{os.getcwd()}")
print(f"当前工作路径下的所有文件有:{os.listdir(os.getcwd())}")

04

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- coding: utf-8 -*-

import timeit


def func():
sum = 0
for i in range(1, 10001):
sum = sum + i
return sum


if __name__ == '__main__':
print(func())
print(f"func函数执行时间为:{timeit.timeit(stmt=func, number=1)}")

05

1
2
3
4
5
6
7
8
9
10
# -*- coding: utf-8 -*-

import numpy as np
import random

array = np.array([[random.randint(1, 100), random.randint(1, 100), random.randint(1, 100), random.randint(1, 100)],
[random.randint(1, 100), random.randint(1, 100), random.randint(1, 100), random.randint(1, 100)],
[random.randint(1, 100), random.randint(1, 100), random.randint(1, 100), random.randint(1, 100)]])
print(array)
print(f"还多维数组所有元素的平均值为:{np.mean(array)}")

06

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- coding: utf-8 -*-

import pandas as pd


data = [['rick', 58], ['jay', 30], ['jj', 28]]
df = pd.DataFrame(data=data, index=['1001', '1002', "1003"], columns=['Name', "Age"])
print(df)
print("第1行的数据为:")
print(df[:1])
print("第2列的数据为:")
print(df[['Name']])
print("第2行第2列的单元格是:")
print(df.loc['1002', 'Name'])

07

1
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np


x = np.arange(1, 20, 1)
plt.plot(x, 2*x + 1, 'red', lw=2)
plt.plot(x, x*x, 'blue', lw=2)
plt.legend([' 2*x + 1', 'x^2'])
plt.show()

08

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- coding: utf-8 -*-

import wordcloud

f = open('springboot.txt', encoding='utf-8')
txt = f.read()

w = wordcloud.WordCloud(width=1000,
height=700,
background_color='white',
font_path='msyh.ttc')
w.generate(txt)
w.to_file('springboot.png')
f.close()

注:springboot.txt文件和08.py文件在同一个文件里

09

自定义模板qingBlog为:

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-


def myprit():
print('qingbo1011')


def mysite():
print('qingbo1011.top')

init.py文件为空

执行代码为:

1
2
3
4
5
6
7
# -*- coding: utf-8 -*-

from 实验七.qingbo import qingBlog


qingBlog.myprit()
qingBlog.mysite()

注:实验七.qingbo为代码所在文件夹位置

实验八

01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- coding: utf-8 -*-

import re


pattern = re.compile('^(13\d|14[5|7]|15\d|166|17[3|6|7]|18\d)\d{8}$')
while 1:
phone = input('请输入电话号码:')
flag = pattern.search(phone)
if flag:
print('电话号码正确')
break
else:
print('电话号码不正确!请重新输入!')
continue

02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# -*- coding: utf-8 -*-

import re


# 1.常规车牌号:仅允许以汉字开头,后面可录入六个字符,由大写英文字母和阿拉伯数字组成。如:粤B12345;
# 2.最后一个为汉字的车牌:允许以汉字开头,后面可录入六个字符,前五位字符,由大写英文字母和阿拉伯数字组成,而最后一个字符为汉字,汉字包括“挂”、“学”、“警”、“港”、“澳”。如:粤Z1234港。
# 3.新军车牌:以两位为大写英文字母开头,后面以5位阿拉伯数字组成。如:BA12345。
pattern = re.compile('^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$')
while 1:
car = input('请输入车牌号:')
flag = pattern.search(car)
if flag:
print('车牌号正确')
break
else:
print('车牌号不正确!请重新输入!')
continue

03

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- coding: utf-8 -*-


import requests
import re


if __name__ == '__main__':
url = 'https://www.sina.com.cn/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36'
}
# 使用爬虫对url对应的一整张页面源代码进行爬取
page_text = requests.get(url=url, headers=headers).text.encode('ISO-8859-1').decode('utf-8')
# print(page_text)
# 使用正则表达式提取出热点
ex = '<li><a target="_blank" href=.*?class="liveNewsLeft photoNewsLeft">(.*?)</a></li>'
title_list = re.findall(ex, page_text, re.M) # 获取新闻标题列表
print("新闻热点为:")
for title in title_list:
print(title)

实验九

01

1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding: utf-8 -*-

with open("gch.txt", "w", encoding="utf-8") as file:
file.write('''观沧海
(曹操)
东临碣石,以观沧海。
水何澹澹,山岛竦峙。
树木丛生,百草丰茂。
秋风萧瑟,洪波涌起。
日月之行,若出其中;
星汉灿烂,若出其里。
幸甚至哉,歌以咏志。''')
print("文件写入完毕!")

02

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
# -*- coding: utf-8 -*-

import random
import numpy as np


lst = [] # 用来存放随机数的列表
for i in range(20): # 循环20次
num = str(random.randint(1, 100)) # 产生1-100之间的随机整数,记得转换成字符串
lst.append(num)


s = ','.join(lst) # 将列表转换成字符串,元素之间用逗号隔开

with open("sjs.txt", "w", encoding="utf-8") as file:
file.write(s)
print('文件写入成功!')
with open("sjs.txt", "r", encoding="utf-8") as file:
string = file.readline()
lst2 = string.split(',') # 字符串以,为切割点,切割成列表
lst3 = [] # 用来存放数字列表
for item in lst2:
num2 = int(item)
lst3.append(num2)
print(f'标准方差为:{np.std(lst3)}')

03

1
2
3
4
5
6
7
# -*- coding: utf-8 -*-

import os


os.system('copy file1.txt file2.txt')
print('复制成功!')

04

1
2
3
4
5
6
# -*- coding: utf-8 -*-

with open('file2.txt', 'a', encoding='utf-8') as file2:
with open('file1.txt', 'r', encoding='utf-8') as file1:
file2.write(file1.read())
print('插入成功!')

05

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
55
56
57
58
59
# -*- coding: utf-8 -*-

import csv


# 文件写入
while 1:
line = input("请分别输入学生的姓名、性别、年龄、语文成绩、数学成绩和英语成绩(用,分隔),输入-1退出:")
if line == '-1':
break
with open('grade.csv', 'a', encoding='utf-8') as grade:
grade.write(line)
grade.write('\n') # 换行

# 文件读取
student_list = [] # 存储学生成绩的列表
with open('grade.csv', 'r', encoding='utf-8') as lines:
for line in lines:
dic = {} # 将每个学生用字典包装起来
line = line.strip() # 消除空白,即换行,得到的每一行的格式为:jay,男,28,87,88,82
a, b, c, d, e, f = line.split(',') # 将字符串以,分割成列表,并用解构的方式分别赋值给abcdef
dic['姓名'] = a
dic['性别'] = b
dic['年龄'] = int(c)
dic['语文成绩'] = int(d)
dic['数学成绩'] = int(e)
dic['英语成绩'] = int(f)
student_list.append(dic) # 字典封装完毕后存储到列表中
# 插入总成绩
for student_dic in student_list:
student_dic['总成绩'] = student_dic['语文成绩'] + student_dic['数学成绩'] + student_dic['英语成绩']
# 按照总成绩排序
for item in student_list:
student_list = sorted(student_list, key=lambda e:e['总成绩'], reverse=True)
# print(student_list)

# 新文件的写入
# 现将要写入的数据以列表形式存放
data_list = []
for student_dic in student_list:
data = []
data.append(student_dic['姓名'])
data.append(student_dic['性别'])
data.append(student_dic['年龄'])
data.append(student_dic['语文成绩'])
data.append(student_dic['数学成绩'])
data.append(student_dic['英语成绩'])
data.append(student_dic['总成绩'])
data_list.append(data)
# print(data_list)


try:
with open('statistics.csv', 'w', encoding='utf-8') as st:
fw = csv.writer(st)
fw.writerows(data_list)
print('写入数据成功!')
except:
print('写入数据失败!')

06

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
# -*- coding: utf-8 -*-


with open('a.txt', 'r') as a:
list_a = []
for s in a:
list_a = list(s) # 获取到a的字符列表

with open('b.txt', 'r') as b:
list_b = []
for s in b:
list_b = list(s) # 获取到a的字符列表

# 排序
list_c = []
for i in list_a:
list_c.append(i)
for i in list_b:
list_c.append(i)
list_c.sort()
# 写入c.txt中
for i in list_c:
with open('c.txt', 'a') as c:
c.write(i)
print('写入数据成功!')

07

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
# -*- coding: utf-8 -*-

import pickle

st = 'hello,world'
lst = [1, 2, 3, 'jj', 'jay']
t = ('python', 'java')
dic = {
'jj': '林俊杰',
'jay': '周杰伦',
'rick': '瑞克'
}
se = {'123', 'hello', 'world'}
data = [666, st, lst, t, dic, se] # 数据列表
# 写入数据
with open('bFile.dat', 'wb') as file:
for item in data:
pickle.dump(item, file)
print('写入数据成功!')
# 读取数据
with open('bFile.dat', 'rb') as file:
data1 = pickle.load(file)
data2 = pickle.load(file)
data3 = pickle.load(file)
data4 = pickle.load(file)
data5 = pickle.load(file)
data6 = pickle.load(file)
print('数字是:', data1)
print('字符串是:', data2)
print('列表是:', data3)
print('元组是:', data4)
print('字典是:', data5)
print('集合是:', data6)
print('读取结束!')

实验十

01

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
# -*- coding: utf-8 -*-


class List_Queue_Exception(BaseException):
msg = ''

def __init__(self, index):
self.msg = f'产生异常:{index}索引超过的队列列表的最大长度!'

def getMsg(self):
return self.msg


class List_Queue:
lst = []

def add(self, a):
self.lst.append(a)
print('添加元素成功!此队列列表为:',queue.lst)

def delete(self, index):
if index > len(self.lst) or index == len(self.lst):
raise List_Queue_Exception(index)
self.lst.pop(index)
print('删除元素成功!此队列列表为:', queue.lst)

def length(self):
print('队列长度为:', len(self.lst))


if __name__ == '__main__':
queue = List_Queue()
try:
while 1:
element = input('请输入要添加到队列的元素(输入-1退出):')
if element == '-1':
break
queue.add(element)
while 1:
i = int(input('请输入要删除元素的索引:(输入-1退出)'))
if i == -1:
break
queue.delete(i)
queue.length()
except List_Queue_Exception as e:
print(e.getMsg())

02

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
# -*- coding: utf-8 -*-

import unittest

class Arithmetic_Operation:
res = 0

def __init__(self, op1, ope, op2):
self.op1 = op1
self.ope = ope
self.op2 = op2
if not (isinstance(self.op1,int) and isinstance(self.op2,int)):
raise Exception('异常:输入的操作数不全为整数!')
if self.ope != '+' and self.ope != '-' and self.ope != '*' and self.ope != '/':
raise Exception('异常:输入操作符无效!')

def operator(self):
if self.ope == '+':
self.res = self.op1 + self.op2
print(f'{self.op1} + {self.op2} = {self.res}')
elif self.ope == '-':
self.res = self.op1 - self.op2
print(f'{self.op1} - {self.op2} = {self.res}')
elif self.ope == '*':
self.res = self.op1 * self.op2
print(f'{self.op1} * {self.op2} = {self.res}')
elif self.ope == '/':
if self.op2 == 0:
raise Exception('异常:输入除数为0!')
self.res = self.op1 / self.op2
print(f'{self.op1} / {self.op2} = {self.res}')


class Test_Arithmetic_Operation(unittest.TestCase):
def test_calculate(self):
while 1:
num1 = int(input('请输入第一个操作数:'))
op = input('请输入操作符(输入$退出):')
if op == '$':
print('退出中...')
break
num2 = int(input('请输入第二个操作数:'))
o1 = Arithmetic_Operation(num1, op, num2)
o1.operator()


if __name__ == '__main__':
unittest.main()

实验十一

01

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# -*- coding: utf-8 -*-

import _sqlite3


class OperateStudentDB:
def __init__(self):
try:
self.conn = _sqlite3.connect('Student.db') # 创建或连接数据库
self.cur = self.conn.cursor()
self.cur.execute('''create table if not exists tb_grade
(sno INTEGER , sname VARCHAR, sex VARCHAR, birthday VARCHAR, maths VARCHAR, english VARCHAR, os VARCHAR);''')
self.conn.commit()
except Exception as e:
print('创建/连接数据库或创建数据表失败', e)

# 添加记录
def add(self, sql):
try:
self.cur.execute(sql)
self.conn.commit()
except Exception as e:
raise e

# 查询记录
def select(self, sql):
try:
cur1 = self.cur.execute(sql)
return cur1
except Exception as e:
raise e

# 更新记录
def update(self, sql):
try:
self.cur.execute(sql)
self.conn.commit()
except Exception as e:
raise e

# 删除记录
def delete(self, sql):
try:
self.cur.execute(sql)
self.conn.commit()
except Exception as e:
raise e

# 析构方法
def __del__(self):
self.cur.close()
self.conn.close()


def menu():
print('---------菜单---------')
print('1.查询记录(按学号)')
print('2.添加记录')
print('3.更新记录')
print('4.删除记录')
print('5.退出')
print('---------菜单---------')


def func1(stu=OperateStudentDB()):
try:
no = int(input('请输入要查询的学生的学号:'))
sql = f'select * from tb_grade where sno = {no}'
cur1 = stu.select(sql)
for row in cur1:
print(f'学号:{row[0]},姓名:{row[1]},性别:{row[2]}出生日期:{row[3]}高等数学成绩:{row[4]}英语成绩:{row[5]}操作系统成绩:{row[6]}')
except Exception as e:
print('查询失败!请检查学号是否输入正确', e)


def func2(stu=OperateStudentDB()):
try:
print('添加记录中,请输入以下信息:')
no = int(input('请输入添加学生学号:'))
name = input('请输入添加学生姓名:')
sex = input('请输入添加学生性别:')
birthday = input('请输入添加学生出生日期:')
math = input('请输入添加学生高等数学成绩:')
english = input('请输入添加学生英语成绩:')
os = input('请输入添加学生操作系统成绩:')
sql = f'insert into tb_grade VALUES ({no},"{name}","{sex}","{birthday}","{math}","{english}","{os}") '
stu.add(sql)
print('添加记录成功!')
except Exception as e:
print('添加记录失败', e)


def func3(stu=OperateStudentDB()):
try:
print('更新记录中,请输入以下信息:')
no = int(input('请输入要更新的学生学号:'))
name = input('请输入更新后学生姓名:')
sex = input('请输入更新后学生性别:')
birthday = input('请输入更新后学生出生日期:')
math = input('请输入更新后学生高等数学成绩:')
english = input('请输入更新后学生英语成绩:')
os = input('请输入更新后学生操作系统成绩:')
sql = f'UPDATE tb_grade SET sname = "{name}", sex = "{sex}", birthday = "{birthday}", maths = "{math}", english = "{english}", os = "{os}" where sno = {no}'
stu.update(sql)
print('更新记录成功!')
except Exception as e:
print('更新记录失败', e)


def func4(stu=OperateStudentDB()):
try:
no = int(input('请输入要删除学生的学号:'))
sql = f'DELETE FROM tb_grade WHERE sno = "{no}"'
stu.delete(sql)
print('删除记录成功!')
except Exception as e:
print('删除记录失败', e)


if __name__ == '__main__':
student = OperateStudentDB()
menu()
while 1:
i = int(input('请输入序号:'))
if i == 1:
func1(student)
continue
elif i == 2:
func2(student)
continue
elif i == 3:
func3(student)
continue
elif i == 4:
func4(student)
continue
elif i == 5:
print('退出中...')
print('退出成功!')
break
else:
print('输入序号无效,请重新输入!')
continue

注:此程序数据库选用的是SqlLite3,其中Student.db文件在创建后应该和01.py文件在同一路径下

02

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# -*- coding: utf-8 -*-

import pymysql


class OperateEmployeeDB:
def __init__(self):
try:
self.conn = pymysql.connect('localhost', '用户名', '密码', 'py_zuoye', 3306)
self.cur = self.conn.cursor()
# 专业表tb_profession和部门表tb_dept已提前创建好
# 查询员工信息表tb_emp是否存在,若不存在,则创建

sql = '''CREATE TABLE IF NOT EXISTS py_zuoye.`tb_emp`(
`eid` INT UNSIGNED AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL,
`sex` VARCHAR(10) NOT NULL,
`birthday` VARCHAR(40) NOT NULL,
`intro` VARCHAR(255) NOT NULL,
`profession` INT NOT NULL,
`dept` INT NOT NULL,
PRIMARY KEY ( `eid` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8'''
self.cur.execute(sql)
self.conn.commit()
print('创建员工信息表tb_emp成功!')
except Exception as e:
print('创建数据库或创建外键失败', e)

# 添加记录
def add(self, sql):
try:
self.cur.execute(sql)
self.conn.commit()
except Exception as e:
raise e

# 查询记录
def select(self, sql):
try:
cur1 = self.cur.execute(sql)
return self.cur
except Exception as e:
raise e

# 更新记录
def update(self, sql):
try:
self.cur.execute(sql)
self.conn.commit()
except Exception as e:
raise e

# 删除记录
def delete(self, sql):
try:
self.cur.execute(sql)
self.conn.commit()
except Exception as e:
raise e

# 析构方法
def __del__(self):
self.cur.close()
self.conn.close()


if __name__ == '__main__':
employee = OperateEmployeeDB() # 创建对象
print('1.添加记录:')
try:
empList = [('100001', 'rick', '男', '1990-10-10', '天才科学家', '2', '3'),
('100002', '沐橙', '女', '1999-10-11', '有丰富的会计工作经历', '4', '7'),
('100003', '派大星', '男', '1995-01-25', '身体强壮,有格斗经验', '6', '11'),
('100004', '王明', '男', '1997-09-19', '名校毕业,法学专业', '10', '5')]
for emp in empList:
addSql = f'insert INTO tb_emp VALUES({emp[0]},"{emp[1]}","{emp[2]}","{emp[3]}","{emp[4]}",{emp[5]},{emp[6]}) '
employee.add(addSql)
print('添加记录成功!')
except Exception as e:
print('添加记录失败', e)

print('2.查询数据:')
try:
id = int(input('请输入要查询的员工编号eid:'))
selectSql = f'select * from tb_emp where eid = {id}'
cur1 = employee.select(selectSql)
print('员工信息如下(专业编号和部门编号见专业表tb_profession和部门表tb_dept):')
# print(cur1.fetchall())
for row in cur1.fetchall():
print(f'编号:{row[0]},姓名:{row[1]},性别:{row[2]},出生日期:{row[3]},个人介绍:{row[4]},专业编号:{row[5]},部门编号:{row[6]}')
except Exception as e:
print('查询失败!请检查姓名是否输入正确', e)

print('3.更新数据:')
try:
print('更新记录中,请输入以下信息:')
no = int(input('请输入要更新的员工编号:'))
name = input('请输入更新后员工姓名:')
sex = input('请输入更新后员工性别:')
birthday = input('请输入更新后员工出生日期:')
math = input('请输入更新后员工个人介绍:')
english = int(input('请输入更新后员工专业编号:'))
os = int(input('请输入更新后员工部门编号:'))
updateSql = f'UPDATE tb_emp SET name = "{name}", sex = "{sex}", birthday = "{birthday}", intro = "{math}", profession = "{english}", dept = "{os}" where eid = {no}'
employee.update(updateSql)
print('更新记录成功!')
except Exception as e:
print('更新记录失败', e)

print('4.删除记录')
try:
no = int(input('请输入要删除员工编号:'))
deleteSql = f'DELETE FROM tb_emp WHERE eid = {no}'
employee.delete(deleteSql)
print('删除记录成功!')
except Exception as e:
print('删除记录失败', e)

注:此程序选用的是MySQL,其中:

1
self.conn = pymysql.connect('localhost', '用户名', '密码', 'py_zuoye', 3306)

用户名和密码分别为mysql的用户名和密码,py_zuoye为所连接数据库名。