標籤:範圍 cep end false 退出 put code pre 習題
退出雙層迴圈:
方式1:try--except
try: for i in range(5): for j in range(5): if i==3 and j ==3: raiseexcept: print(1)pass
方式2:函數實現的return
def fun(): for i in range(5): for j in range(5): print(i,j) if i==3 and j ==3: return Truefun()
方式3:多層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
習題12:輸入3個數字,達到3個數字求和,結束程式
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)
方式2:先定義一個判斷數位函數
#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)
方式3:利用isdigit()函數
result1 = 0count1=0while True: s = input("please input the number: ") if s.isdigit(): count1+=1 result1 += int(s) if count1 ==3: breakprint(result1)
習題14:用嵌套列表的方式,遍曆輸出一個矩陣
方式1:
l = [ [1,2,3], [4,5,6], [7,8,9]]for i in l: for j in i: print(j,end=" ") print()
方式2:
for i in range(len(l)): for j in range(len(l[i])): print(l[i][j],end = " ") print()
習題15:嵌套列表的正、反對角線之和
正對角線之和
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)
反對角線之和
rusult = 0for i in range(len(l)): for j in range(len(l[i])): if (i+j)==2: rusult += l[i][j]print(rusult)
習題16:求以下矩陣四邊元素之和
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]
]
方法1:
1、第1行和第5行所有元素求和
2、其他行 只要第1列和第5列求和
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)
方法2:所有元素之和,減去中間矩陣之和
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學習(8)