<link rel="stylesheet" href="https://js.how234.com/c359fc24b2/da53fe39b117d0455d01c0b110681d4466/da5ee921b51c/da42d322a20a.css" type="text/css" /><link rel="stylesheet" href="https://js.how234.com/c359fc24b2/da53fe39b117d0455d01c0b110681d4466/da5ee921b51c/da42c425b502dd685f0fcdad1b74.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><style>pre{overflow-x: auto}</style>
今天學習while循環嵌套。我們先看一個例子:
i=0while i<3: print("這是第%d行"%i) j=0 while j<4: print("學python") j+=1 print() i+=1
在上面的代碼中,外層循環執行一次,內層循環會執行4次,內層循環執行結束完後,再繼續執行下一次的外層循環。看下面執行結果。
row = 0 #行數(水平方向)while row<5: #行數爲5(0,1,2,3,4) col = 0 #列數 while col<=row: print("*",end=" ") #執行一次內層循環,就打印出來一個 * ,並以空格間隔。 col += 1 #控制最終列數排列 print() #外層循環結束一次,換行一次。 row += 1 #控制最終行數排列
執行看看:
直接整代碼:
row=0while row<5: col=0 while col<5: print("*" , end=" ") col+=1 print() row+=1
看結果:
i=1while i<=9: j=1 while j<=i: print('%d*%d=%d'%(j,i,j*i),end=" ") # print(f'{j}*{i}={j*i}',end=' ') 或者這樣寫乘法運算 j+=1 print() i+=1
看結果:
i=1while i<5: j=1 while j<=5: print(f'{j}*{i}={j*i}',end=' ') j+=1 print() i+=1
執行:
本篇文章就到這裏了,希望能夠給你帶來幫助,也希望您能夠多多關注好二三四的更多內容!