Python新手教程之while循環(huán)20例
介紹
循環(huán)是計算機編程中最常用的結構之一。在Python中,有兩種類型的循環(huán):while循環(huán)和for循環(huán)。在本文中,我們將專注于while循環(huán)并提供20個實用示例,幫助您了解while循環(huán)的基本概念和用法。
Example 1: 簡單的while循環(huán)
這是一個最簡單的while循環(huán),它只打印數字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語句用于跳過當前循環(huán)的剩余語句并繼續(xù)下一次循環(huán)。在下面的示例中,我們跳過了所有奇數并打印了所有偶數:
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)計算輸入數字的階乘:
num = int(input("輸入一個數字: "))
factorial = 1
i = 1
while i <= num:
factorial *= i
i += 1
print(f"{num} 的階乘是 {factorial}")Example 6: 使用while循環(huán)計算斐波那契數列
在下面的示例中,我們使用while循環(huán)計算斐波那契數列:
num = int(input("輸入一個數字:"))
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)實現石頭剪刀布游戲
在下面的示例中,我們使用while循環(huá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)實現猜數字游戲
在下面的示例中,我們使用while循環(huán)實現猜數字游戲:
import random
print("歡迎來到猜數字游戲!")
number = random.randint(1, 20)
guesses = 0
while guesses < 6:
guess = int(input("請輸入一個數字:"))
guesses += 1
if guess < number:
print("你猜的數字太小了。")
elif guess > number:
print("你猜的數字太大了。")
else:
print(f"恭喜你,你猜對了!你用了 {guesses} 次猜中了數字。")
break
else:
print(f"很遺憾,你沒有猜中數字。數字是 {number}。")Example 10: 使用while循環(huán)實現加法練習
在下面的示例中,我們使用while循環(huán)實現加法練習:
import random
print("歡迎來到加法練習!")
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)實現倒計時
在下面的示例中,我們使用while循環(huán)實現倒計時:
import time
countdown = 10
while countdown > 0:
print(countdown)
time.sleep(1)
countdown -= 1
print("時間到!")Example 12: 使用while循環(huán)實現打印圖案
在下面的示例中,我們使用while循環(huán)實現打印圖案:
i = 1
while i <= 5:
print("*" * i)
i += 1Example 13: 使用while循環(huán)實現計數器
在下面的示例中,我們使用while循環(huán)實現計數器:
counter = 0
while True:
print(counter)
counter += 1
if counter == 10:
breakExample 14: 使用while循環(huán)實現密碼驗證
在下面的示例中,我們使用while循環(huán)實現密碼驗證:
password = "bazinga"
while True:
attempt = input("請輸入密碼:")
if attempt == password:
print("密碼正確!")
break
else:
print("密碼錯誤,請重試。")Example 15: 使用while循環(huán)實現文件讀取
在下面的示例中,我們使用while循環(huán)實現文件讀?。?/p>
with open("example.txt") as f:
line = f.readline()
while line:
print(line.strip())
line = f.readline()Example 16: 使用while循環(huán)實現文件寫入
在下面的示例中,我們使用while循環(huá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)實現字符串反轉
在下面的示例中,我們使用while循環(huá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)實現列表反轉
在下面的示例中,我們使用while循環(huá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)實現字符串切片
在下面的示例中,我們使用while循環(huá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)實現列表切片
在下面的示例中,我們使用while循環(huá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)的概念,并在實踐中應用它們。
附:經典題目水仙花數
(從0至999之間各個位數的立方和等于本身的數等于水仙花數)代碼:
#include <stdio.h>
int main (void)
{
int i=0; //定義初始值數
int a,b,c; //定義個位數百位數
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í)行語句塊內容,拆解i的個位百位數,在用if語句判斷是否成立,成立就輸出i;
3、判斷i的值,拆分個位十位百位;a = i/100; //百位; b = i/10%10; //十位;c = i%10; //個位
4、重復上面的操作,直到i=1000時,條件不成立,直接跳出while循環(huán),運行while下面的語句。
結果:

總結
到此這篇關于Python新手教程之while循環(huán)20例的文章就介紹到這了,更多相關Python while循環(huán)實例內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python使用OpenCV對彩色圖像進行通道分離的項目實踐
通道分離是將彩色圖像的每個像素分解為三個通道(紅、綠、藍)的過程,本文主要介紹了Python使用OpenCV對彩色圖像進行通道分離的項目實踐,感興趣的可以了解一下2023-08-08
Python OpenCV實現傳統(tǒng)圖片格式與base64轉換
Base64是網絡上最常見的用于傳輸8Bit字節(jié)碼的編碼方式之一,本文主要介紹了Python OpenCV實現傳統(tǒng)圖片格式與base64轉換,感興趣的可以參考一下2021-06-06

