省略,代码详见教材。
答案:
radius = float(input("请输入园的半径:"))
# 直径
diameter = 2 * radius
# 面积
area = 3.14 * radius * radius
print('园的直径为:', diameter)
print('园的面积为:', area)
答案:
frequency = (29.5 - 4 * 3) / 2.5
print("还需运送的次数为:",frequency)
num = 0
while num <= 100:
if num % 2 == 0:
print(num)
num += 1
num = int(input("请输入一个数:"))
if num > 0:
print("输入的数是正数")
elif num < 0:
print("输入的数是负数")
else:
print("输入的书是零")
i = 2
for i in range(2, 100):
j = 2
for j in range(2, i):
if i % j == 0:
break
else:
print(i)
答案:
s = 'AbcDeFGhIJ'
count = 0
for i in s:
for j in s.lower():
if i==j:
count+=1
print(count)
答案:
string = " Life is short. I use python"
if string.find('python'):
new_string =string.replace('python','Python')
print(new_string)
else:
print(string)
答案:
li_num1 = [4, 5, 2, 7]
li_num2 = [3, 6]
li_num1.extend(li_num2)
li_num1.sort(reverse=True)
print(li_num1)
答案:
tu_num1 = ('p', 'y', 't', ['o', 'n'])
tu_num1[len(tu_num1)-1].append('h')
print(tu_num1)
答案:
dict_data = dict()
string= 'skdaskerkjsalkj'
for elem in string:
if elem not in dict_data.keys():
dict_data[elem] = 1
else:
dict_data[elem] = dict_data[elem] + 1
print(dict_data)
答案:
li_one = [1,2,1,2,3,5,4,3,5,7,4,7,8]
new_li =[]
for i in li_one:
if i not in new_li:
new_li.append(i)
print(new_li)
答案:
def event_num_sum():
result = 0
counter = 1
while counter <= 100:
counter += 1
if counter % 2 == 1:
continue
result += counter
return result
print(event_num_sum())
答案:
def func(num):
if num == 2:
return 1
else:
return num * func(num - 1)
result = func(20)
print(result)
答案:
def is_palindrome():
num = input('请输入整数:\n')
palindrome_num = num[::-1]
return num == palindrome_num
print(is_palindrome())
答案:
def triangle():
side_length_one = int(input("请输入第一个边长:\n"))
side_length_two = int(input("请输入第二个边长:\n"))
side_length_three = int(input("请输入第三个边长:\n"))
if (side_length_one + side_length_two > side_length_three and
side_length_one + side_length_three > side_length_two and
side_length_two + side_length_three > side_length_one):
return "能构成三角形"
else:
return "不能构成三角形"
print(triangle())
答案:
def lcm(x, y):
# 获取最大的数
if x > y:
greater = x
else:
greater = y
while True:
if greater % x == 0 and greater % y == 0:
lcm = greater
break
greater += 1
return lcm
# 获取用户输入
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))
print(num1, "和", num2, "的最小公倍数为", lcm(num1, num2))
答案:
def file_read():
data_li = []
with open('file.txt', 'r',encoding='utf8') as file:
for data in file.readlines():
if not data.startswith('#'):
data_li.append(data)
return data_li
print(file_read())
答案:
passwordBook = {}
def add(password, value):
if password not in passwordBook.keys():
passwordBook[password] = value
save()
else:
print("该密码已存在")
def delete(password):
if password in passwordBook.keys():
del passwordBook[password]
print(passwordBook)
save()
else:
print("该密码不存在")
def modify(password, newValue):
if password in passwordBook.keys():
passwordBook[password] = newValue
print(passwordBook)
save()
else:
print("该密码不存在")
def find(value):
if value in passwordBook.values():
print("该网址存在")
else:
print("该网址不存在")
def save():
f = open("password.txt","w")
f.write(str(passwordBook))
f.close()
def printInfo():
print("密码簿的功能如下:")
print("1.添加")
print("2.删除")
print("3.修改")
print("4.查找")
i = 0
while i<5:
printInfo()
num = int(input("请输入要选择的功能:"))
if num==1:
web = input("请输入存入的网址:")
password1 = input("请输入密码:")
add(password1, web)
print(passwordBook)
elif num==2:
password2 = input("请输入密码:")
delete(password2)
elif num==3:
password3 = input("请输入密码:")
value3 = input("请输入新的网址:")
modify(password3,value3)
elif num==4:
value4 = input("请输入要查找的网址:")
find(value4)
i+=1
答案:
def num_sort():
file_li = []
num_li = []
with open('num.txt', 'r', encoding='utf8') as file:
data = file.readlines()
for i in data:
file_li.append(i.split(' '))
for file_elem in file_li:
for elem in file_elem:
if elem.find('\n'):
new_elem = elem.replace('\n', '')
num_li.append(int(new_elem))
else:
num_li.append(int(elem))
num_li.sort()
print(num_li)
num_sort()
答案:
class Circle:
def __init__(self,tup, radius, color):
self.center = tup
self.radius = radius
self.color = color
def perimeter(self):
return 3.14 * 2 * self.radius
def area(self):
return 3.14 * self.radius * self.radius
circle = Circle((0,0),5,"蓝色")
print(circle.perimeter())
print(circle.area())
答案:
class Course:
def __init__(self):
self.number = 1001
self.name = "语文"
self.teacher = "张老师"
self.__location = "2号教学楼3层305室"
def show_info(self):
return ("""
课程编号:%d
课程名称:%s
任课教师:%s
上课地点:%s
""" % (self.number, self.name, self.teacher, self.__location))
course = Course()
print(course.show_info())
答案:
class NumericalError(Exception):
def __init__(self):
self.message = '请输入正确的数据'
class CircleArea:
def circle(self):
try:
radius = int(input("请输入圆的半径:\n"))
if radius <0:
raise NumericalError()
except NumericalError as e:
print(e.message)
else:
# 计算圆的面积
print(3.14*radius**2)
circle_area = CircleArea()
circle_area.circle()
答案:
class MessageError(Exception):
def __init__(self):
self.no_message = '不能构成三角形'
class Triangle:
def composed_triangle(self):
side_length_one = int(input("请输入第一个边长:\n"))
side_length_two = int(input("请输入第二个边长:\n"))
side_length_three = int(input("请输入第三个边长:\n"))
try:
if not (side_length_one + side_length_two > side_length_three and
side_length_one + side_length_three > side_length_two and
side_length_two + side_length_three > side_length_one):
raise MessageError()
except MessageError as e:
print(e.no_message)
else:
print('可以构成')
triangle = Triangle()
triangle.composed_triangle()
答案:
import turtle
'''全局变量'''
amount = 10 #词频排列显示个数
words = [] #单词集合-x轴数据
wCounts = [] #单词频数集合-y轴数据
xPoint = -360
yPoint = -200
'''turtle start'''
#绘制从点(x1,y1)到(x2,y2)的线段
def drawLine(t,x1,y1,x2,y2):
t.penup()
t.goto(x1,y1)
t.pendown()
t.goto(x2,y2)
#在坐标(x,y)处写文字
def drawText(t,x,y,text,fontSize=10):
t.penup()
t.goto(x,y)
t.pendown()
t.write(text,font=('微软雅黑',fontSize,),align='center')
#绘制矩形
def drawRectangle(t,x,y,rWidth):
drawLine(t,x-rWidth,yPoint,x-rWidth,y)
drawLine(t,x-rWidth,y,x+rWidth,y)
drawLine(t,x+rWidth,y,x+rWidth,yPoint)
drawLine(t,x+rWidth,yPoint,x-rWidth,yPoint)
#绘制柱状图
def drawBarchart(t):
drawText(t,0,-yPoint-40,"词频统计结果",15) #绘制标题
drawRectangle(t,0,-yPoint,-xPoint) #绘制边框
rWidth = -xPoint/(2*amount) #控制条形柱宽度(2rWidth)
xScale = -xPoint*2/(amount+1) #x轴显示放大倍数-可根据amount进行调节
yScale = -yPoint/wCounts[0] #y轴显示放大倍数-可根据频数进行调节
for i in range(amount):
i=i+1 #右移以避免与原点重合
x=i*xScale+xPoint
y=wCounts[i-1]*yScale+yPoint
drawText(t,x,yPoint-20,words[i-1]) #打印单词
drawText(t,x,y+10,wCounts[i-1]) #打印频率
t.begin_fill()
drawRectangle(t,x,y,rWidth)
t.end_fill()
#初始化窗口
def init():
turtle.title('词频结果柱状图')
turtle.screensize(900,750,"#272727")
t=turtle.Turtle()
t.hideturtle() #隐藏箭头
t.width(1) #线条粗细
t.color("#EBEBD0","#006030")
#t.color("#006030","#FFF68C")
drawBarchart(t) #绘制
turtle.exitonclick()
'''data Processing'''
#对文本的每一行计算词频的函数
def processLine(line,wordamounts):
line = replacePunctuations(line) #用空格替换标点符号
words = line.split() #从每一行获取每个词
for word in words:
if word in wordamounts:
wordamounts[word] += 1
else:
wordamounts[word] = 1
#空格替换标点
def replacePunctuations(line):
for ch in line:
if ch in "~!@#$%^&*()-_+=<>?/,.:;{}[]|\'\"":
line = line.replace(ch,' ')
return line
#数据处理,得到文件中出现频率最高的单词及其频数
def dataProcess(filename):
infile=open(filename,'r',encoding='UTF-8')
wordamounts={} #建立用于记录词频的空字典
for line in infile:
processLine(line.lower(),wordamounts)
pairs = list(wordamounts.items()) #从字典中获取数据对
items = [[x,y]for (y,x) in pairs] #列表中的数据对交换位置,使频数成为元素的键值
items.sort() #列表排序。默认根据键值排序
#输出amount个词频结果
for i in range(len(items)-1,len(items)-amount-1,-1):
print(items[i][1]+"\t"+str(items[i][0]))
wCounts.append(items[i][0])
words.append(items[i][1])
infile.close()
def main():
#用户输入一个文件名
filename= input("enter a filename:").strip()
dataProcess(filename)
init()
#调用main()函数
if __name__ == '__main__':
main()
答案:
import wordcloud
from matplotlib.image import imread
font = 'AdobeHeitiStd-Regular.otf'
# 用于生成词云的字符串
with open('葫芦兄弟.txt','r',encoding='utf-8')as file:
string = str(file.read())
# 词云形状
mk = imread('葫芦娃.jpg')
# 创建词云对象
w = wordcloud.WordCloud(font_path=font, mask=mk,
max_words=500,background_color='white')
# 加载文本
w.generate(string)
# 生成词云
w.to_file('葫芦娃.png')