第7章:用户输入和while循环(User Input and While Loops)
一、导读
1.1 本章学习目标
第7章介绍如何让程序与用户交互。本章核心目标:
- 掌握input()函数:获取用户输入
- 熟练使用while循环:实现重复执行
- 理解标志和break/continue:控制循环流程
- 学会处理用户输入验证:确保输入正确
- 掌握在列表间移动元素:while循环的实际应用
1.2 为什么本章如此重要
交互式程序是实际应用的常态。while循环提供了比for循环更灵活的重复执行方式,特别适合处理不确定次数的循环。
1.3 核心问题引导
input()返回的是什么类型?如何处理数字输入?
while循环和for循环各自适合什么场景?
如何避免无限循环?
break和continue有什么区别?
二、核心概念详解
7.1 input()函数
python
# 基本输入
name = input("Enter your name: ")
print(f"Hello, {name}!")
# 数字输入(需要类型转换)
age_str = input("Enter your age: ")
age = int(age_str)
print(f"Next year you will be {age + 1}")
# 多行输入提示
prompt = "Please enter your favorite color: "
prompt += "(or 'quit' to exit) "
color = input(prompt)7.2 while循环
python
# 基本while循环
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
# 使用标志
active = True
while active:
message = input("Enter something (or 'quit' to exit): ")
if message == 'quit':
active = False
else:
print(f"You said: {message}")
# break和continue
while True:
item = input("Enter item (or 'done'): ")
if item == 'done':
break
if item == '':
continue
print(f"Added: {item}")7.3 在列表间移动元素
python
# 从未确认移到已确认
unconfirmed = ["alice", "bob", "charlie"]
confirmed = []
while unconfirmed:
current = unconfirmed.pop()
print(f"Confirming: {current}")
confirmed.append(current)
print("\nConfirmed users:")
for user in confirmed:
print(user.title())
# 删除特定元素
pets = ["dog", "cat", "dog", "goldfish", "cat", "rabbit"]
while "cat" in pets:
pets.remove("cat")
print(pets)7.4 输入验证
python
# 验证数字输入
while True:
try:
number = int(input("Enter a number between 1-10: "))
if 1 <= number <= 10:
break
print("Number must be between 1 and 10")
except ValueError:
print("Please enter a valid number")
print(f"You entered: {number}")
# 验证用户名
def get_valid_username():
while True:
username = input("Enter username (3-20 chars): ")
if 3 <= len(username) <= 20:
return username
print("Username must be 3-20 characters")
name = get_valid_username()
print(f"Username: {name}")三、实战案例
3.1 猜数字游戏
python
import random
def guess_number():
secret = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("=== Guess the Number ===")
print("I'm thinking of a number between 1 and 100.")
while attempts < max_attempts:
try:
guess = int(input(f"Attempt {attempts + 1}/{max_attempts}: "))
except ValueError:
print("Please enter a valid number")
continue
attempts += 1
if guess == secret:
print(f"Congratulations! You guessed it in {attempts} attempts!")
return True
elif guess < secret:
print("Too low!")
else:
print("Too high!")
print(f"Game over! The number was {secret}")
return False
# 运行游戏
while True:
guess_number()
play_again = input("Play again? (y/n): ")
if play_again.lower() != 'y':
break四、本章小结
第7章介绍了用户交互:input()获取输入、while循环实现重复执行、break/continue控制流程、输入验证。
五、思考与练习
思考题
input()总是返回字符串,如何安全地转换为数字?
while True循环和带条件的while循环各有什么优缺点?
如何在while循环中处理异常?
编程练习
实现一个简单的命令行计算器。
编写一个待办事项管理器(添加、完成、删除、显示)。
实现一个文本菜单系统。