首页 > 解决方案 > 检查条件是否立即得到尊重

问题描述

我有一个复杂的项目,我将尝试简化项目的主要问题之一。所以有一个简化:我们可以想象一个这样的while循环:

while(condition):
     statement1
     statement2
     statement3
     ...
     statementn

在这个循环中有 n 个语句,每个语句可以是任何语句(函数、循环、if 语句,...),并且循环中有一个条件,这个条件我想在 while 循环执行之前检查它。因为如果条件是自第一个语句以来的尊重,我必须等到 while 结束才能检查条件是否尊重......所以我的问题是可以在没有检查功能的情况下在循环之前检查条件在 whileloop 的每个语句之间?

因为事实上,它可以工作......但是代码并不清楚,我真的认为这样我们会污染我的代码,我想更有效地工作并且使用漂亮的代码,那么如果没有这个约束,我该如何解决我的问题呢?

PS:我想到了像javascript这样的事件监听器,但我在python上发现关于它们的信息很差,但是如果有一个像事件监听器一样的工具,那就太好了!

标签: pythonevents

解决方案


It sounds like you want to clean up all your if-then-break statements into a single function that handles the "checking" of the value of a. For that purpose you could use exceptions:

import random

class ItIsFiveException(Exception): pass

def check(a):
  if a == 5:
    raise ItIsFiveException

try:
  a = 0
  while(a != 5):
    a = random.randint(1,5); check(a)
    a = random.randint(1,5); check(a)
    a = random.randint(1,5); check(a)
    a = random.randint(1,5); check(a)
except ItIsFiveException:
  print("I saw a five!")

You just have to define your own python Exception as a class, and the raise it in your manually-defined check(a) function. Then you can wrap your entire while loop in a try-except block and catch your exception.


推荐阅读