python_base_while循环、for循环
生活随笔
收集整理的這篇文章主要介紹了
python_base_while循环、for循环
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在程序的三大流程,一共有三種流程方式:
1、順序---從上向下,順序執行代碼
2、分支---根據條件判斷,決定執行代碼的 分支
3、循環---讓 特定代碼 重復 執行
除非需求的特殊要求,否則循環的計數都從0開始
i=0
while i<5:
print("hello python")
i+=1
print("循環結束后,i = %d " %i)
輸出結果:
hello python
hello python
hello python
hello python
hello python
循環結束后,i = 5
i=0
#定義最終結果的變量
result=0
#開始循環
while i <=100:
print(i)
result +=i
i+=1
print("0-100的求和結果是%d" %result)
輸出結果:
0
1
2
3
4
5
6
7
8
9
10
0-100的求和結果是55
result=0
i=0
while i <= 10:
#判斷變量i中的數值,是否是一個偶數
if i % 2 ==0:
print(i)
result+=i
i+=1
print("1-10的偶數累加結果是%d" %result)
輸出結果:
0
2
4
6
8
10
1-10的偶數累加結果是30
for n in range(1,m+1):
print("{0}*{1}={2}".format(m,n,m*n),end="\t")
print()
1、順序---從上向下,順序執行代碼
2、分支---根據條件判斷,決定執行代碼的 分支
3、循環---讓 特定代碼 重復 執行
除非需求的特殊要求,否則循環的計數都從0開始
i=0
while i<5:
print("hello python")
i+=1
print("循環結束后,i = %d " %i)
輸出結果:
hello python
hello python
hello python
hello python
hello python
循環結束后,i = 5
計算0-10 之間的所有數字的累積求和結果。
#定義一個整數的變量記錄循環的次數i=0
#定義最終結果的變量
result=0
#開始循環
while i <=100:
print(i)
result +=i
i+=1
print("0-100的求和結果是%d" %result)
輸出結果:
0
1
2
3
4
5
6
7
8
9
10
0-100的求和結果是55
?計算0-10 之間的所有數字的累積求和結果。
#定義一個記錄最終結果的變量result=0
i=0
while i <= 10:
#判斷變量i中的數值,是否是一個偶數
if i % 2 ==0:
print(i)
result+=i
i+=1
print("1-10的偶數累加結果是%d" %result)
輸出結果:
0
2
4
6
8
10
1-10的偶數累加結果是30
?打印九九乘法表:
?問題:
發現第3列并沒有對齊。
【解決方案】end=" " 改成 end="\t" 即可
?
知識點:
\t? 在控制臺輸出一個制表符,協助在輸出文本對垂直方向保持對齊。
\n 在控制臺輸出換行符。
\" 在控制臺輸出雙引號。
?
另一種方式:
for m in range(1,10):for n in range(1,m+1):
print("{0}*{1}={2}".format(m,n,m*n),end="\t")
print()
?
for循環?
?
轉載于:https://www.cnblogs.com/tianpin/p/10120452.html
總結
以上是生活随笔為你收集整理的python_base_while循环、for循环的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Eugeny and Array(水题,
- 下一篇: IOC使用