python - 检查条件是否立即得到尊重
问题描述
我有一个复杂的项目,我将尝试简化项目的主要问题之一。所以有一个简化:我们可以想象一个这样的while循环:
while(condition):
statement1
statement2
statement3
...
statementn
在这个循环中有 n 个语句,每个语句可以是任何语句(函数、循环、if 语句,...),并且循环中有一个条件,这个条件我想在 while 循环执行之前检查它。因为如果条件是自第一个语句以来的尊重,我必须等到 while 结束才能检查条件是否尊重......所以我的问题是可以在没有检查功能的情况下在循环之前检查条件在 whileloop 的每个语句之间?
因为事实上,它可以工作......但是代码并不清楚,我真的认为这样我们会污染我的代码,我想更有效地工作并且使用漂亮的代码,那么如果没有这个约束,我该如何解决我的问题呢?
PS:我想到了像javascript这样的事件监听器,但我在python上发现关于它们的信息很差,但是如果有一个像事件监听器一样的工具,那就太好了!
解决方案
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.
推荐阅读
- node.js - 无法在 Express App 中获取客户 IP 地址
- html - 如何让我的图像在 CSS 中通过?
- php - 如何为某个字段具有某个值的所有产品提取 xml 数据?
- admob - 可以使用实时 Admob 代码在测试设备上运行 Admob 广告吗?
- unity3d - 当我打开口型同步选项卡时,Unity 检查器 GUI 坏了
- c++ - 如何使用 Boost MSM 检索包含状态机
- javascript - 编译失败:找不到模块
- logging - Athena 经典负载均衡器日志
- sql - Oracle - to_date() 解析为 00:00:00
- php - response()->json 无法在 Laravel 中解码