Python新手教程之while循環(huán)20例
介紹
循環(huán)是計算機編程中最常用的結(jié)構(gòu)之一。在Python中,有兩種類型的循環(huán):while循環(huán)和for循環(huán)。在本文中,我們將專注于while循環(huán)并提供20個實用示例,幫助您了解while循環(huán)的基本概念和用法。
Example 1: 簡單的while循環(huán)
這是一個最簡單的while循環(huán),它只打印數(shù)字1到5:
i = 1
while i <= 5:
print(i)
i += 1Example 2: 無限循環(huán)
這個例子展示了如何創(chuàng)建一個無限循環(huán),需要使用break語句來退出循環(huán):
while True:
x = input("輸入 'stop' 來停止循環(huán): ")
if x == 'stop':
breakExample 3: 使用continue語句
continue語句用于跳過當(dāng)前循環(huán)的剩余語句并繼續(xù)下一次循環(huán)。在下面的示例中,我們跳過了所有奇數(shù)并打印了所有偶數(shù):
i = 0
while i < 10:
i += 1
if i % 2 != 0:
continue
print(i)Example 4: 循環(huán)中的else語句
在Python中,循環(huán)中的else語句與if語句中的else語句相似。它們在循環(huán)完成時執(zhí)行。在下面的示例中,我們使用else語句在循環(huán)完成時打印一條消息:
i = 1
while i <= 5:
print(i)
i += 1
else:
print("循環(huán)已完成")
Example 5: 使用while循環(huán)計算階乘
在下面的示例中,我們使用while循環(huán)計算輸入數(shù)字的階乘:
num = int(input("輸入一個數(shù)字: "))
factorial = 1
i = 1
while i <= num:
factorial *= i
i += 1
print(f"{num} 的階乘是 {factorial}")Example 6: 使用while循環(huán)計算斐波那契數(shù)列
在下面的示例中,我們使用while循環(huán)計算斐波那契數(shù)列:
num = int(input("輸入一個數(shù)字:"))
a, b = 0, 1
while b < num:
print(b)
a, b = b, a + bExample 7: 使用while循環(huán)查找列表中的元素
在下面的示例中,我們使用while循環(huán)查找列表中的元素:
fruits = ["蘋果", "香蕉", "櫻桃", "葡萄"]
i = 0
while i < len(fruits):
print(fruits[i])
i += 1Example 8: 使用while循環(huán)實現(xiàn)石頭剪刀布游戲
在下面的示例中,我們使用while循環(huán)實現(xiàn)石頭剪刀布游戲:
import random
print("歡迎來到石頭剪刀布游戲!")
options = ["石頭", "剪刀", "布"]
computer_choice = random.choice(options)
while True:
player_choice = input("請輸入石頭、剪刀或布:")
if player_choice not in options:
print("輸入無效,請重新輸入。")
continue
print(f"電腦的選擇是:{computer_choice}")
if player_choice == computer_choice:
print("平局!")
elif (player_choice == "石頭" and computer_choice == "剪刀") or (player_choice == "剪刀" and computer_choice == "布") or (player_choice == "布" and computer_choice == "石頭"):
print("你贏了!")
else:
print("你輸了!")
breakExample 9: 使用while循環(huán)實現(xiàn)猜數(shù)字游戲
在下面的示例中,我們使用while循環(huán)實現(xiàn)猜數(shù)字游戲:
import random
print("歡迎來到猜數(shù)字游戲!")
number = random.randint(1, 20)
guesses = 0
while guesses < 6:
guess = int(input("請輸入一個數(shù)字:"))
guesses += 1
if guess < number:
print("你猜的數(shù)字太小了。")
elif guess > number:
print("你猜的數(shù)字太大了。")
else:
print(f"恭喜你,你猜對了!你用了 {guesses} 次猜中了數(shù)字。")
break
else:
print(f"很遺憾,你沒有猜中數(shù)字。數(shù)字是 {number}。")Example 10: 使用while循環(huán)實現(xiàn)加法練習(xí)
在下面的示例中,我們使用while循環(huán)實現(xiàn)加法練習(xí):
import random
print("歡迎來到加法練習(xí)!")
correct_answers = 0
total_questions = 0
while True:
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
answer = int(input(f"{num1} + {num2} = "))
total_questions += 1
if answer == num1 + num2:
correct_answers += 1
print("回答正確!")
else:
print("回答錯誤。")
if input("是否繼續(xù)?(y/n)") == "n":
break
print(f"你回答了 {total_questions} 道題目,其中 {correct_answers} 道題目回答正確。")Example 11: 使用while循環(huán)實現(xiàn)倒計時
在下面的示例中,我們使用while循環(huán)實現(xiàn)倒計時:
import time
countdown = 10
while countdown > 0:
print(countdown)
time.sleep(1)
countdown -= 1
print("時間到!")Example 12: 使用while循環(huán)實現(xiàn)打印圖案
在下面的示例中,我們使用while循環(huán)實現(xiàn)打印圖案:
i = 1
while i <= 5:
print("*" * i)
i += 1Example 13: 使用while循環(huán)實現(xiàn)計數(shù)器
在下面的示例中,我們使用while循環(huán)實現(xiàn)計數(shù)器:
counter = 0
while True:
print(counter)
counter += 1
if counter == 10:
breakExample 14: 使用while循環(huán)實現(xiàn)密碼驗證
在下面的示例中,我們使用while循環(huán)實現(xiàn)密碼驗證:
password = "bazinga"
while True:
attempt = input("請輸入密碼:")
if attempt == password:
print("密碼正確!")
break
else:
print("密碼錯誤,請重試。")Example 15: 使用while循環(huán)實現(xiàn)文件讀取
在下面的示例中,我們使用while循環(huán)實現(xiàn)文件讀取:
with open("example.txt") as f:
line = f.readline()
while line:
print(line.strip())
line = f.readline()Example 16: 使用while循環(huán)實現(xiàn)文件寫入
在下面的示例中,我們使用while循環(huán)實現(xiàn)文件寫入:
with open("example.txt", "w") as f:
while True:
line = input("請輸入一行文本:")
if line == "quit":
break
f.write(line + "\\n")Example 17: 使用while循環(huán)實現(xiàn)字符串反轉(zhuǎn)
在下面的示例中,我們使用while循環(huán)實現(xiàn)字符串反轉(zhuǎn):
text = "Hello, World!"
reversed_text = ""
i = len(text) - 1
while i >= 0:
reversed_text += text[i]
i -= 1
print(reversed_text)Example 18: 使用while循環(huán)實現(xiàn)列表反轉(zhuǎn)
在下面的示例中,我們使用while循環(huán)實現(xiàn)列表反轉(zhuǎn):
fruits = ["蘋果", "香蕉", "櫻桃", "葡萄"]
reversed_fruits = []
i = len(fruits) - 1
while i >= 0:
reversed_fruits.append(fruits[i])
i -= 1
print(reversed_fruits)Example 19: 使用while循環(huán)實現(xiàn)字符串切片
在下面的示例中,我們使用while循環(huán)實現(xiàn)字符串切片:
text = "Hello, World!"
substring = ""
start = 7
end = 12
i = start
while i < end:
substring += text[i]
i += 1
print(substring)Example 20: 使用while循環(huán)實現(xiàn)列表切片
在下面的示例中,我們使用while循環(huán)實現(xiàn)列表切片:
fruits = ["蘋果", "香蕉", "櫻桃", "葡萄"]
sliced_fruits = []
start = 1
end = 3
i = start
while i < end:
sliced_fruits.append(fruits[i])
i += 1
print(sliced_fruits)在本文中,我們介紹了Python中的while循環(huán)及其用法,并提供了20個實用示例。這些示例可以幫助您更好地理解while循環(huán)的概念,并在實踐中應(yīng)用它們。
附:經(jīng)典題目水仙花數(shù)
(從0至999之間各個位數(shù)的立方和等于本身的數(shù)等于水仙花數(shù))代碼:
#include <stdio.h>
int main (void)
{
int i=0; //定義初始值數(shù)
int a,b,c; //定義個位數(shù)百位數(shù)
while( i<=999) //條件
{
//開始拆解個位、十位、百位;
a = i/100; //百位
b = i/10%10; //十位
c = i%10; //個位
if (a*a*a+b*b*b+c*c*c == i) //if語句判斷條件
{
printf("水仙花:%d\n",i); //為真輸出語句塊
}
i++; //再計算i,后面返回while
}
return 0;
}解釋:
1、開始確定區(qū)間【0-999】
2、開始執(zhí)行 i = 0;條件成立,執(zhí)行語句塊內(nèi)容,拆解i的個位百位數(shù),在用if語句判斷是否成立,成立就輸出i;
3、判斷i的值,拆分個位十位百位;a = i/100; //百位; b = i/10%10; //十位;c = i%10; //個位
4、重復(fù)上面的操作,直到i=1000時,條件不成立,直接跳出while循環(huán),運行while下面的語句。
結(jié)果:

總結(jié)
到此這篇關(guān)于Python新手教程之while循環(huán)20例的文章就介紹到這了,更多相關(guān)Python while循環(huán)實例內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python使用OpenCV對彩色圖像進(jìn)行通道分離的項目實踐
通道分離是將彩色圖像的每個像素分解為三個通道(紅、綠、藍(lán))的過程,本文主要介紹了Python使用OpenCV對彩色圖像進(jìn)行通道分離的項目實踐,感興趣的可以了解一下2023-08-08
Python實現(xiàn)操作Redis所有類型的方法詳解
Redis作為一款高性能的NoSQL數(shù)據(jù)庫,越來越受到了廣大開發(fā)者的喜愛。本篇博客將介紹如何使用Python操作Redis的所有類型,以及一些高級用法,感興趣的可以了解一下2023-04-04
Python數(shù)據(jù)分析之Matplotlib的常用操作總結(jié)
Matplotlib是Python的繪圖庫,它可與NumPy一起使用,提供了一種有效的MatLab開源替代方案,下面這篇文章主要給大家介紹了關(guān)于Python數(shù)據(jù)分析之Matplotlib常用操作的相關(guān)資料,需要的朋友可以參考下2022-01-01
Python OpenCV實現(xiàn)傳統(tǒng)圖片格式與base64轉(zhuǎn)換
Base64是網(wǎng)絡(luò)上最常見的用于傳輸8Bit字節(jié)碼的編碼方式之一,本文主要介紹了Python OpenCV實現(xiàn)傳統(tǒng)圖片格式與base64轉(zhuǎn)換,感興趣的可以參考一下2021-06-06

