Python中的while
循环是一种基本的循环结构,它会在条件为真时反复执行代码块。while
循环的语法如下:
while condition:
# 执行代码块
这里的condition
是一个布尔表达式,如果其值为True
,则执行缩进的代码块。每次执行完代码块后,会重新评估条件表达式,如果仍然为True
,则继续执行循环体。当条件表达式为False
时,循环停止。
常见的用法
执行固定次数的循环:
count = 5 while count > 0: print("Count:", count) count -= 1
无限循环:
while True: # 执行代码块,直到外部条件(如用户输入)触发退出 user_input = input("Enter 'exit' to quit: ") if user_input == 'exit': break
使用
break
和continue
语句:numbers = [1, 2, 3, 4, 5, 6] while True: current = numbers.pop(0) if current == 3: continue # 跳过当前迭代,继续下一次迭代 if current > 5: break # 条件不满足时退出循环 print(current)
等待条件满足:
import time from threading import Event stop_event = Event() def stop_thread(): stop_event.set() thread = threading.Thread(target=stop_thread) thread.start() while not stop_event.is_set(): print("Thread is running...") time.sleep(1) print("Thread has stopped.")
经典的应用案例
模拟用户登录尝试:
用户有限定次数尝试登录,超过次数则锁定账户。MAX_ATTEMPTS = 3 attempts = 0 while attempts < MAX_ATTEMPTS: username = input("Enter username: ") password = input("Enter password: ") if valid_login(username, password): print("Login successful!") break else: attempts += 1 print(f"Invalid credentials. Attempts left: {MAX_ATTEMPTS - attempts}") if attempts == MAX_ATTEMPTS: print("Account locked!") break
读取文件直到文件末尾:
打开一个文件,并逐行读取内容,直到文件结束。filename = 'example.txt' with open(filename, 'r') as file: while True: line = file.readline() if not line: break print(line, end='') # 打印每一行内容
实现简单的聊天机器人:
允许用户与机器人对话,直到用户选择退出。print("Welcome to the chatbot! Type 'exit' to quit.") while True: message = input("You: ") if message.lower() == 'exit': print("Chatbot: Goodbye!") break response = chatbot_response(message) print(f"Chatbot: {response}")
while
循环是处理不确定次数的迭代和等待特定条件发生时的理想选择。通过结合break
和continue
语句,可以灵活地控制循环的执行流程。