欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2022年12月22日 11:19:22   作者:Python熱愛者  
Python中除了for循環(huán)之外還有一個(gè)while循環(huán),下面這篇文章主要給大家介紹了關(guān)于Python基礎(chǔ)教程之while循環(huán)用法講解的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下

1.while 循環(huán)

Python 中 while 語句的一般形式:

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

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

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

以下實(shí)例使用了 while 來計(jì)算 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)

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

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

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

請(qǐng)輸入一個(gè)數(shù)字:1
您輸入的數(shù)字是1
請(qǐng)輸入一個(gè)數(shù)字:3
您輸入的數(shù)字是3
請(qǐng)輸入一個(gè)數(shù)字:4
您輸入的數(shù)字是4
請(qǐng)輸入一個(gè)數(shù)字:

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

無限循環(huán)在服務(wù)器上客戶端的實(shí)時(shí)請(qǐng)求非常有用。

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

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

語法格式如下:

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

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

循環(huán)輸出數(shù)字,并判斷大?。?/p>

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、簡(jiǎn)單語句組

類似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
.......

附小練習(xí):

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é)

到此這篇關(guān)于Python基礎(chǔ)教程之while循環(huán)用法講解的文章就介紹到這了,更多相關(guān)Python while循環(huán)用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論