条件成立时重复执行
while 循环在每一轮之前检查条件,只要条件为 True 就执行代码块。当你事先不知道需要几轮时就用它:把订单不断减半直到足够小、等待价格突破某个水平、让余额增长到目标值。代码块里必须有东西改变条件,否则循环永远不会结束。
# Halve an order until it is small enough to trade at once
quantity, limit = 1000, 100
steps = 0
while quantity > limit:
quantity = quantity / 2
steps += 1
print(steps, quantity) # 4 62.5用 for 还是 while?
已经有这些元素或知道数量时用 for:它不会无限运行。停止点取决于循环过程中发生的事情时用 while。一个简单的判断:如果你会说“对其中每一个”,就写 for;如果你会说“直到这个条件成立”,就写 while。
确保循环能够结束运行
while 循环之前检查三件事:条件用到了循环会修改的变量;每一轮都会修改;并且修改使条件朝 False 靠近。如果某个循环在这里运行太久,10 秒后会被强制停止。break:立即退出循环
break 会立即结束循环,并从循环之后的那一行继续。当你已经得到答案(例如第一个突破限价的价格)时,就用它来提前停止。这里的循环用一个由它自己递增的索引来遍历各个位置。
# break leaves the loop at once
prices = [184.25, 184.5, 186.0, 185.0]
limit = 185.5
index = 0
while index < len(prices):
if prices[index] > limit:
print("breach at", index) # breach at 2
break
index += 1continue:跳到下一轮
continue 会跳过本轮剩余的代码,回到条件判断。用它可以忽略无效数据,而不必把真正的处理逻辑嵌套进 if 里。在 while 循环中,要在 continue 之前更新循环变量,否则循环会永远卡在同一个元素上。
# continue skips the rest of the pass; step first, or it never moves on
fills = [100, -5, 250, 0, 75]
total = 0
index = 0
while index < len(fills):
value = fills[index]
index += 1
if value <= 0:
continue
total += value
print(total) # 425用于搜索或收敛的循环
量化中的许多任务都是“一直做到……”:复利增长到目标、不断改进估计直到不再变化、重试直到请求成功。当退出判断位于处理过程中间时,常见的写法是 while True: 并在中间放一个 break。
# How many years until 10,000 grows to 15,000 at 7% a year?
balance, target, rate = 10_000, 15_000, 0.07
years = 0
while balance < target:
balance = balance * (1 + rate)
years += 1
print(years) # 6
# while True + break: the exit test sits in the middle
attempt = 0
while True:
attempt += 1
if attempt * 25 >= 100:
break
print(attempt) # 4- 条件使用了循环会修改的变量。
- 每一轮都会修改,即使是在
continue之前。 - 一旦得到答案就用
break。
下一节:定义与调用函数,给一段代码起个名字并重复使用。
实验:评分内容
- 用
halving_steps统计订单需要减半的次数25 分 - 用
first_breach找到第一个超过限价的价格25 分 - 用
sum_until_zero累加有效成交直到结束标记25 分 - 用
years_to_target把余额复利增长到目标值25 分