首页 > 解决方案 > 如何在以下代码中为每个 while 循环采用不同的 r 值?python

问题描述

import random
class check_error:
def __init__(self,firstbyte=bytearray(b'\x15\x04\xA5')) :
    r=random.choice (firstbyte)
    self.r=r

def pocket_data(self):


    print("I am sending request for NBP/SpO2 datas")
    r=self.r

    while True:    
        print("blala")
        r=self.r
        print(r)

        try: 
            if int("{:02x}".format(r))==15:
                print("Negative Acknowledgment.Error occured during data transmission to device.I am sending the datas again... ")
                continue

            elif r==4:
                print("Host does not have the capability to respond to the request,it only supports a subset of the protocol")
                continue

        except:
            print("done")
            break   

s=check_error()
print(s.pocket_data())

如果选择的元素是 x15 或 x04,则循环变得无穷无尽,但我想做的是选择 bytearray 的不同元素,直到选择的元素是 xA5。

标签: pythonloopsclasswhile-loop

解决方案


初始化类时,r设置为random.choice (firstbyte). 请注意,这永远不会改变;您设置 的值r,然后分配self.r = r,然后您再也不会更改self.r

如果您想r继续滚动随机数,您需要做的是保存firstbyte到类中的变量中 - 例如:

def __init__(self,firstbyte=bytearray(b'\x15\x04\xA5')) :
    self.firstbyte = firstbyte
    r=random.choice (firstbyte)
    self.r=r

然后,在循环内部,继续以与构造函数中相同的方式生成随机数:

while True:    
    self.r = random.choice(self.firstbyte)
    ...

推荐阅读