1.打印圆的面积
调包,把π引进来,然后用round函数保留小数
import math
round(S,n) #n为要保留的几位小数
2.打印素数
#python中的for循环和C里面的不太一样
for number in range(a,b):
#number在a到b-1里面遍历,且后面要加冒号,不要忘记了,定义的函数后面也要加冒号
3.打印一个数组的和
#如果是一个数组传进来那么它遍历与普通遍历不太一样,直接用in
for i in para_list(数组名)
for i range para_list这是错误的写法
4.排序
students=[
{"sno":101,"sname":"校长","grade":88},
{"sno":102,"sname":"蔡徐坤","grade":89},
{"sno":103,"sname":"张三","grade": 82},
{"sno":104,"sname":"李斯","grade": 83},
]
student_sort=sorted(students,key=lambda x:x["grade"]) #keyd代表着怎样比较,x代表着按照"grade"进行比较,而后面加一个reverse=True为倒序排列
print(student_sort)
5.读取文件进行操作
排序:
def read_file():
result=[]
with open("./students_grades.txt",encoding='UTF-8') as fin:
for line in fin:
line=line[:-1] #[:-1]代表的是去掉源文件中的换行符
result.append(line.split(","))
return result
def write_files(datas):
with open("./students_grades_output.txt","w",encoding='UTF-8') as fout:
for data in datas:
fout.write(",".join(data))
datas=read_file()
student_sort=sorted(datas,key=lambda x:int(x[2]),reverse=True)
write_files(student_sort)
进行计算:
def compute_score():
scores=[]
with open("./students_grades.txt") as fin:
for line in fin:
line=line[:-1]
fields=line.split(",")
scores.append(float(fields[-1])) #-1代表是最后一个元素
max_score=max(scores)
min_score=min(scores)
avg_score=round(sum(scores)/len(scores),2)
return max_score,min_score,avg_score
max_score,min_score,avg_score=compute_score()
print(max_score)
print(min_score)
print(avg_score)