日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Python基礎教程之while循環(huán)用法講解_python

作者:Python熱愛者 ? 更新時間: 2023-01-27 編程語言

1.while 循環(huán)

Python 中 while 語句的一般形式:

while 判斷條件(condition):
? ? 執(zhí)行語句(statements)……

執(zhí)行流程圖如下:

同樣需要注意冒號和縮進。另外,在 Python 中沒有 do…while 循環(huán)。

以下實例使用了 while 來計算 1 到 100 的總和:

n = 100
sum = 0
count = 1

while count <= n:
    sum = sum + count
    count = count + 1

print("1加到100的和為%d" % sum)

執(zhí)行結(jié)果:

1加到100的和為5050

2.無限循環(huán)

我們可以通過設置條件表達式永遠不為 false 來實現(xiàn)無限循環(huán),實例如下:

while True:
    num = int(input("請輸入一個數(shù)字:"))
    print("您輸入的數(shù)字是%d" % num)

執(zhí)行結(jié)果:

請輸入一個數(shù)字:1
您輸入的數(shù)字是1
請輸入一個數(shù)字:3
您輸入的數(shù)字是3
請輸入一個數(shù)字:4
您輸入的數(shù)字是4
請輸入一個數(shù)字:

你可以使用 CTRL+C 來退出當前的無限循環(huán)。

無限循環(huán)在服務器上客戶端的實時請求非常有用。

3、while 循環(huán)使用 else 語句

如果 while 后面的條件語句為 false 時,則執(zhí)行 else 的語句塊。

語法格式如下:

while <expr>:
? ? <statement(s)>
else:
? ? <additional_statement(s)>

expr 條件語句為 true 則執(zhí)行 statement(s) 語句塊,如果為 false,則執(zhí)行 additional_statement(s)。

循環(huán)輸出數(shù)字,并判斷大小:

count = 0
while count <5:
    print("count小于5:", count)
    count = count + 1
else:
    print("count大于5了:", count)

執(zhí)行結(jié)果:

count小于5: 0
count小于5: 1
count小于5: 2
count小于5: 3
count小于5: 4
count大于5了 5

4、簡單語句組

類似if語句的語法,如果你的while循環(huán)體中只有一條語句,你可以將該語句與while寫在同一行中, 如下所示:

flag = 1
while (flag): 
	print("hello.yin")

print("hello.yin! good bye~")

執(zhí)行結(jié)果:

hello.yin
hello.yin
hello.yin
hello.yin
hello.yin
hello.yin
.......

附小練習:

1.求1+2+3+…+100的和

sum = 0
i = 1
while  i <=100:
    sum += i
    i += 1
print(sum)

輸出結(jié)果:

2.求1~100的偶數(shù)和

sum = 0
n = 1
while n < 100:
? ? if n % 2 == 0:
? ? ? ? sum = sum + n

? ? n += 1
print("1-100之間偶數(shù)的和是: ", sum)

輸出結(jié)果:

總結(jié)

原文鏈接:https://blog.csdn.net/qdPython/article/details/124045455

欄目分類
最近更新