0%

三种循环形式和iter函数的使用

在编程中,循环是一个常见的结构,用于重复执行某个动作直到满足特定条件。本文以一个简单的猜数字游戏为例,介绍了三种不同的循环方式以及如何使用 iter 函数来优化代码。

1. 使用 while True 循环

最基本的方式是使用 while True 循环,这种方法通过在循环内部使用 break 语句终止循环。例如:

1
2
3
4
5
6
7
8
9
10
while True:
guess = int(input("Enter an integer(1-100) : "))

if guess == NUMBER:
print("Congratulations, you guessed it.")
break
elif guess < NUMBER:
print("No, it is a little higher than that.")
else:
print("No, it is a little lower than that.")

虽然这种方法很常见,但它有一个“坏味道”,因为 while True 暗示了一个无限循环,可能会导致代码难以理解和维护。

2. 使用赋值表达式优化 while 循环

Python 3.8 引入了赋值表达式(即“海象运算符”:=),可以将输入和条件检查合并,避免使用 while True:

1
2
3
4
5
6
while (guess := int(input("Enter an integer(1-100) : "))) != NUMBER:
if guess < NUMBER:
print("No, it is a little higher than that.")
else:
print("No, it is a little lower than that.")
print("Congratulations, you guessed it.")

这种方式减少了代码的冗余,使得循环条件更加明确。

3. 使用 iter 函数和 for 循环

iter 函数可以将一个可调用对象转换为生成器,并通过传入一个哨兵值来控制生成器的终止。使用 iter 函数,我们可以用 for 循环来替代 while 循环:

1
2
3
4
5
6
7
for guess in iter(lambda: int(input()), NUMBER):
if guess < NUMBER:
print("No, it is a little higher than that.")
else:
print("No, it is a little lower than that.")

print("Congratulations, you guessed it.")

与 while True 循环相比,for 循环在代码审查中更具有说服力,因为它更清晰地表达了循环的结束条件。

使用 iter 函数实现附加功能

iter 函数的另一个优势是它可以很容易地结合 enumerate 函数来实现附加功能,例如统计猜测次数:

1
2
3
4
5
6
7
8
for times, guess in enumerate(iter(lambda: int(input()), NUMBER), start=1):
if guess < NUMBER:
print(f"No, it is a little higher than that. Wrong Guess Times: {times}")
else:
print(f"No, it is a little lower than that. Wrong Guess Times: {times}")


print(f"Congratulations, you guessed it. Wrong Guess Times: {times}")

相比之下,使用 while 循环则需要手动维护一个计数变量,这增加了代码的复杂性。

1
2
3
4
5
6
7
8
9
times = 0
while (guess := int(input("Enter an integer(1-100) : "))) != NUMBER:
times += 1
if guess < NUMBER:
print(f"No, it is a little higher than that. Wrong Guess Times: {times}")
else:
print(f"No, it is a little lower than that. Wrong Guess Times: {times}")

print(f"Congratulations, you guessed it. Wrong Guess Times: {times}")

总结

本文通过实例介绍了如何在 Python 中使用不同的循环结构,特别是如何利用 iter 函数优化代码。通过减少对 while True 循环的依赖,代码将更易读、更易维护。希望读者在未来的编程中能够灵活应用这些技巧。

扫码加入技术交流群🖱️
QR code