python - 如何激活 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)
解决方案
鉴于您修复了缩进,并在需要时使用 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。你应该根据你的要求实现这些东西程序,这是您可以这样做的两种方式。
推荐阅读
- android - 如何从我的 ViewModel 类访问我的服务类?
- ubuntu - 如何在不使用 Auditd 或默认 Ubuntu 安装的情况下在 Ubuntu 中进行流程审核?
- git - Git中的版本编号文件夹是不好的做法吗?
- r - 快速单击操作按钮时,observeEvent 和 update*Input 之间的竞争
- c# - C# await 关键字是否会导致函数调用阻塞?
- r - How to multiply variables inplace in a dataframe of a long format?
- python - 如何使用 geomdl 或其他库向样条曲线添加边界约束?
- javascript - js 将表单数据从 https 发布到 http
- couchbase - 从 Couchbase 中的动态数组字段中获取数据
- python - 如何编写可以多次启动的单个进程类?