python:每个tim打印一条消息

2024-09-29 01:29:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码,应该每次打印一条消息:

if pitch > 0 and  pitch < 180 :
    print "forward"

if pitch > -180 and pitch < 0 :
    print "backward"

if yaw  < 0 and  yaw > -180 :
    print "left"

if yaw  < 180 and yaw  > 0 :
    print "right"

if (yaw == yawN )and (pitch == pitchN) :
    print "stable"

我一次收到两条信息

forward
left
forward
left
forward
left

我该怎么做才能每次发一条信息呢?你知道吗


Tags: and代码right信息消息ifleftforward
3条回答

这是因为它可以向前和向左(例如)。所以你总会收到两条信息。你知道吗

我们可以使用if-elif获得如下所示的所需输出:

if pitch > 0 and  pitch < 180 :
    print "forward"

elif pitch > -180 and pitch < 0 :
    print "backward"

elif yaw  < 0 and  yaw > -180 :
    print "left"

elif yaw  < 180 and yaw  > 0 :
    print "right"

elif (yaw == yawN )and (pitch == pitchN) :
    print "stable"

else:
    print "default"

看看这是否有用!你知道吗

您将得到一条yaw的消息和一条pitch的消息,因为您没有采取任何措施来阻止这种情况的发生,您可以通过将if替换为elif来打印一条消息,如下所示:

if pitch > 0 and  pitch < 180 :
    print "forward"

elif pitch > -180 and pitch < 0 :
    print "backward"

elif yaw  < 0 and  yaw > -180 :
    print "left"

elif yaw  < 180 and yaw  > 0 :
    print "right"

else :
    print "stable"

然而,这不太可能达到你想要的效果,因为你真的想要一个1度的俯仰角和175度的偏航角组合成“向前”吗?相反,您可能希望比较值的大小(abs(pitch)将返回大小),然后将响应基于具有更高大小的值,如下所示:

if pitch == 0 and yaw == 0 :
    # Eliminate the stable option first to cut down on comparisons
    print("stable")

elif abs(pitch) > abs(yaw) :
    # If we're pitching more than yawing, only give the pitch message
    if pitch > 0 :
        print "forward"
    else :
        print "backward"

else :
    # The other options have been eliminated, so we must be yawing more than pitching
    if yaw  < 0 :
        print "left"

    else :
        print "right"

(我假设你的角度保持在-180 < theta <= 180范围内;如果不是,你可能应该这样做)

尽管您可能还需要一组混合消息,用于在两个方向上都有重要输入的情况,因此如果偏航为90,俯仰为90,则会报告类似于“向右前进”的消息。你知道吗

相关问题 更多 >