首页 > 解决方案 > 如何激活 while true 语句

问题描述

所以我想在我的代码中添加一个 while True 语句,这样当变量为假时它不起作用,但当变量更改为真时它会激活。在我的情况下,我有一个打开的 cv 摄像头,女巫扫描 QR 码并想知道如何激活它,因为它使用了一个 while true 语句。有任何想法吗。下面的例子

hello = false
r = input("hello or hi: ")
if r == 'hi':
hello = True
     while hello = True:
    _, img = cap.read()
    data, bbox, _ = detector.detectAndDecode(img)
    if bbox is not None:
        for i in range(len(bbox)):
            cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i + 1) % len(bbox)][0]), color=(255, 0, 0), thickness=2)

标签: pythonfunctioninputwhile-loop

解决方案


鉴于您修复了缩进,并在需要时使用 break 语句停止循环,上述内容也应该可以正常工作。https://docs.python.org/2.0/ref/break.html

hello = false
r = input("hello or hi: ")
if r == 'hi':
    hello = True
while hello = True:
    _, img = cap.read()
    data, bbox, _ = detector.detectAndDecode(img)
    if bbox is not None:
        for i in range(len(bbox)):
            cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i + 1) % len(bbox)][0]), color=(255, 0, 0), thickness=2)
    break

现在应该根据您的需要实施休息。每当调用 break 时,您的循环将终止,因此您可以在 if 语句中实现它,或者在循环结束时实现它,具体取决于您的使用情况。

您也可以使用 if 语句来检查变量是否为真,然后才运行 while 循环。当您想要在 while 语句中使用不同的条件时,它会很有用。

hello = false
r = input("hello or hi: ")
if r == 'hi':
    hello = True
if hello:
    j = 1
    while j < 5:
        _, img = cap.read()
        data, bbox, _ = detector.detectAndDecode(img)
        if bbox is not None:
            for i in range(len(bbox)):
                cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i + 1) % len(bbox)][0]), color=(255, 0, 0), thickness=2)
        j += 1

在上面的代码中,while 循环只会在 hello 变量为 True 时执行,然后 while 循环会不断迭代,直到 j 的值等于或大于 5。你应该根据你的要求实现这些东西程序,这是您可以这样做的两种方式。


推荐阅读