1.输入3个数字,达到3个数字求和,结束程序。
result = 0
for i in range(3):
result += int(input("please input a number:"))
print(result)
执行结果:
2.用户输入不同的数据,当输入的数据达到3个数字的时候,求和结束程序。(数字可以是整数)
提示:判断是否整数的方法,isdigit()
遍历所有的输入数据,判断是否在0-9的字符串范围内
def isdigit(s):
for i in s:
if i not in "0123456789":
return False
return True
result= 0
times= 0
while 1:
input_data = input("请输入数据:")
if isdigit(input_data):
result+=int(input_data)
times+=1
if times == 3:
break
print(result)
def isdigit(data):
try:
float(data)
return True
except:
return False
print(isdigit("1"))
print(isdigit("1.999999"))
print(isdigit("1/3"))
print(isdigit("5c"))
print(isdigit(""))
print(isdigit(1))
3.用嵌套列表的方式来输出一个矩阵
1 2 3
4 5 6
7 8 9
[[1,2,3],[4,5,6],[7,8,9]]
方法1:
l = [[1,2,3],[4,5,6],[7,8,9]]
for i in l:
for j in i:
print(j,end=" ")
print("")
l = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(l)):
for j in range(len(l[i])):
print(l[i][j],end=" ")
print("")
l = [[1,2,3],[4,5,6],[7,8,9]]
result = 0
for i in range(len(l)):
for j in range(len(l[i])):
if i == j:
result+=l[i][j]
print(result)
l = [[1,2,3],[4,5,6],[7,8,9]]
result = 0
for i in range(len(l)):
for j in range(len(l[i])):
if i+j ==2:
result+=l[i][j]
print(result)
求下列矩阵边上的数之和
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
算法1:行号为0和4的所有元素都要相加
否则,只加第一个和最后一个
l = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
result = 0
for i in range(len(l)):
for j in range(len(l[i])):
if i == 0 or i == 4:
result += l[i][j]
else:
if j == 0 or j == 4:
result += l[i][j]
print(result)