Exit the Double loop:
Way 1:try--except
try: for i in range(5): for j in range(5): if i==3 and j ==3: raiseexcept: print(1)pass
Mode 2: Return of function implementation
def fun(): for i in range(5): for j in range(5): print(i,j) if i==3 and j ==3: return Truefun()
Mode 3: Multi-layer break
for i in range(5): for j in range(5): for k in range(5): if i == j == k == 3: break else: print (i, ‘----‘, j, ‘----‘, k) else: continue break else: continue break
Exercise 12: Enter 3 digits to sum up to 3 numbers, ending the program
result = 0for i in range(3): number = input("please input number: ") result += int(number)print(result)习题13、 用户输入不同的数据,当输入的数据达到3个数字的时候,求和结束程序。(数字可以是整数)提示:判断是否整数的方法,isdigit()遍历所有的输入数据,判断是否在0-9的字符串范围内方式1: #coding=utf-8result = 0count = 0while True: s = input("please input the number: ") for v in s: if v not in "0123456789":#如果不是数字跳出当前循环 break else: count+=1 result += int(s) if count ==3: breakprint(result)
Method 2: First define a function to judge the number
#encoding=utf-8def is_int(num): for n in num: if n not in "0123456789": return Falsereturn Trueresult = 0number_count = 0while True: s = input("please input the number: ") if is_int(s): result += int(s) number_count += 1 if number_count == 3: break print(result)
Method 3: Use the IsDigit () function
result1 = 0count1=0while True: s = input("please input the number: ") if s.isdigit(): count1+=1 result1 += int(s) if count1 ==3: breakprint(result1)
Exercise 14: Iterating through the output of a matrix with nested lists
Mode 1:
l = [ [1,2,3], [4,5,6], [7,8,9]]for i in l: for j in i: print(j,end=" ") print()
Mode 2:
for i in range(len(l)): for j in range(len(l[i])): print(l[i][j],end = " ") print()
Exercise 15: The sum of the positive and inverse diagonals of nested lists
The sum of the positive diagonal
l = [ [1,2,3], [4,5,6], [7,8,9] ]rusult = 0for i in range(len(l)): for j in range(len(l[i])): if i==j: rusult += l[i][j]print(rusult)
The sum of the inverse diagonal
rusult = 0for i in range(len(l)): for j in range(len(l[i])): if (i+j)==2: rusult += l[i][j]print(rusult)
Exercise 16: Finding the sum of the four elements of the matrix
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]
]
Method 1:
1, line 1th and line 5th all elements sum
2. Other rows as long as the 1th and 5th columns are summed
rusult = 0for i in range(len(l)): for j in range(len(l[i])): if i == 0 or i == 4: rusult += l[i][j] else: if j==0 or j==4: rusult += l[i][j]print(rusult)
Method 2: Sum of all elements minus the sum of the intermediate matrices
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] ]matrix_element_sum = 0sub_matrix_element_sum = 0for i in range(len(l)): for j in range(len(l[i])): matrix_element_sum += l[i][j]result_mid = 0for i in range(len(l)): for j in range(len(l[i])): if i == 0 or i ==4: continue else: if j !=0 and j!=4: sub_matrix_element_sum += l[i][j]print(matrix_element_sum - sub_matrix_element_sum)
Python Learning (8)