(Python第三天)实例

一、判断学生成绩是否达标的程序

 1 n = int(input("Enter the number of students:"))#输入学生数目
 2 data = {}   #用来存储数据的字典变量
 3 Subjects = ('Physics','Maths','History') #元组,定义所有科目
 4 for i in range(0,n):
 5     name = input('Enter the name of the student {}:'.format(i + 1))#获得学生名称
 6     marks = []
 7     for x in Subjects:
 8         marks.append(int(input('Enter marks of {}:'.format(x))))#获得分数
 9     data[name] = marks#把分数存储到data中
10     for x,y in data.items():
11         total = sum(y)
12         print("{}'s total marks {}".format(x,total))
13         if total < 120:
14             print(x,"failes :(")
15         else:
16             print(x, "passed :)")

 ps:sum()函数是对系列进行求和计算,实例如下:

>>>sum([0,1,2])

3

>>>sum((2,3,4),1)   #元组计算总和后再加1

10

 

 

二、计算两个矩阵的乘积

 1 #计算两个矩阵的Hadamard成绩,就是矩阵乘法,要求输入矩阵的行列数,假设是n * n矩阵
 2 
 3 n = int(input("Enter the value of n:"))
 4 print("Enter values for the Matrix A")
 5 a = []
 6 for i in range(n):
 7     a.append([int(x) for x in input().split()])
 8 print("Enter values for the Matrix B")
 9 b = []
10 for i in range(n):
11     b.append([int(x) for x in input().split()])
12 c = []
13 for i in range(n):
14     c.append([a[i][j] * b[i][j] for j in range(n)])
15 print("After matrix multiplication")
16 print("-" * 7 * n)
17 for x in c:
18     for y in x:
19         print(str(y).rjust(5),end=' ')
20     print()
21 print("-" * 7 * n)

ps:str()函数

str函数是将对象转化为适于人阅读的形式,即返回一个对象的string格式。

2)rjust方法

rjust()返回一个原字符串右对齐,并使用空格填充至长度width的新字符串,语法是:

str.rjust(width[, fillchar])

如:

str = "baobao,this is a example!!"
print(str.rjust(50,'*'))

结果:

************************baobao,this is a example!!

3)split()分割字符串得到一系列的数字字符串  

 

posted @ 2019-01-16 21:54  ywangji  阅读(172)  评论(0编辑  收藏  举报