循环破解问题(Python)

Env*_*lap 1 python loops while-loop

我目前正在尝试连接GPS蓝牙设备.我的Python 2.7代码最初工作正常,但我现在尝试将我的代码实现为while循环,这样,当我的设备不可用时,它将继续为它循环.不幸的是,我的代码似乎陷入了循环并反复打印出错误消息"无法找到蓝牙GPS设备.正在重试......"我正在使用PyBluez的蓝牙模块.

这是我的代码: -

import bluetooth

target_address = "00:11:22:33:44:55:66"

discovered_devices = discover_devices()  # Object to discover devices from Bluetooth module

while True:
    print "Attempting to locate the correct Bluetooth GPS Device..."
    for address in discovered_devices:
        if address != target_address:
            print "Unable to Locate Bluetooth GPS Device. Retrying..."
        else:
            print "Bluetooth GPS Device Located: ", target_address
            break

# move on to next statement outside of loop (connection etc...)
Run Code Online (Sandbox Code Playgroud)

如上所述,基本上我想要实现的是设备发现对象启动,并在控制台上显示一条消息,指示它正在寻找发送指定设备地址的设备(即"00:11:22:33:44: 55:66" ).如果没有设备有此地址,我希望代码提供与无法找到设备有关的错误消息,然后我希望它继续继续查找.

另一方面,我最终还是想编辑这段代码,以便在尝试定位设备X时间/多次X次但无济于事之后,我希望代码结束和程序提供错误消息.对此有何指导?

谢谢

Sim*_*mon 5

这条线

discovered_devices = discover_devices()
Run Code Online (Sandbox Code Playgroud)

while在进入for循环之前,应该进入循环内部.

然后while通过for循环替换循环以限制尝试次数.

为了正确退出内for循环,请按@Jeremy说:添加

else:
    continue
break
Run Code Online (Sandbox Code Playgroud)

在它的最后.

您可能还希望在外循环的每次迭代中每次尝试之间等待sleep().