Appearance
循环——for / while,break / continue
概念讲解
循环就是重复执行一段代码。编程中大量重复性工作都靠循环完成。
两种循环:
for:遍历一个已知的序列(列表、字符串、范围等)while:在条件为真时一直循环,不知道要循环多少次时用
控制循环的关键字:
break:跳出整个循环continue:跳过当前迭代,进入下一次循环
代码示例
遍历:统计文章中的关键词
python
article = """
Python is a powerful programming language.
Python is widely used in data science.
Many developers love Python for its simplicity.
"""
target_word = "Python"
count = 0
for word in article.split():
# 去除标点
clean_word = word.strip(".,!?")
if clean_word == target_word:
count += 1
print(f'"{target_word}" 出现了 {count} 次')
# 输出: "Python" 出现了 3 次while:猜数字游戏
python
import random
secret = random.randint(1, 100)
max_attempts = 7
print("猜一个1到100之间的数字,你有7次机会!")
for attempt in range(1, max_attempts + 1):
guess = int(input(f"第{attempt}次(还剩{max_attempts - attempt + 1}次):"))
if guess == secret:
print(f"恭喜!猜对了!用了{attempt}次")
break
elif guess < secret:
print("太小了,往大猜")
else:
print("太大了,往小猜")
else:
# for循环正常结束(没有break)时执行
print(f"次数用完了!正确答案是 {secret}")嵌套循环:打印乘法表
python
for i in range(1, 10):
row = []
for j in range(1, i + 1):
row.append(f"{j}×{i}={i*j}")
print(" ".join(row))练习题
题目:有一串整数,找出其中第二大的数(不允许用排序)。
例如:[5, 1, 9, 6, 8, 7, 2] → 输出 8(最大是9,第二大是8)
参考答案
python
def second_max(numbers):
if len(numbers) < 2:
return None
max_num = second = float('-inf')
for num in numbers:
if num > max_num:
second = max_num
max_num = num
elif num > second and num != max_num:
second = num
return second
print(second_max([5, 1, 9, 6, 8, 7, 2])) # 8
print(second_max([9, 9, 8, 8])) # 9(两个9并列最大)
print(second_max([1, 2])) # 1关键思维:
- 一遍遍历解决,用两个变量跟踪最大和第二大
float('-inf')是最小的数,保证任何数都比它大elif num > second and num != max_num:避免重复计入最大值