这是我正在为我的大学项目中的机器人编写的代码。这段代码有效,但是循环会不断地每秒打印一次语句,我希望它只在我改变输入条件时打印(打破if条件),所以它不会继续打印。有没有什么办法解决这一问题?我在这里先向您的帮助表示感谢。
PS:这是在python 2.7(我认为)
try:
while True:
#some stuff
if 0.01 < joystick.get_axis(1) <= 0.25:
print ('moving backward with 25% speed')
# performing some actions
elif 0.25 < joystick.get_axis(1) <= 0.5:
print ('moving forward with 50% speed')
# performing some actions
elif 0.5 < joystick.get_axis(1) <= 0.75:
print ('moving backward with 75% speed')
# performing some actions
while循环以相同的方式继续......
答案 0 :(得分:1)
跟踪最后一个类别 - 类似的东西。
previous_category = 0
while True:
#some stuff
if 0.01 < joystick.get_axis(1) <= 0.25:
if previous_category != 1:
print ('moving backward with 25% speed')
previous_category = 1
# performing some actions
elif 0.25 < joystick.get_axis(1) <= 0.5:
if previous_category != 2:
print ('moving forward with 50% speed')
previous_category = 2
# performing some actions
elif 0.5 < joystick.get_axis(1) <= 0.75:
if previous_category != 3:
print ('moving backward with 75% speed')
previous_category = 3
# performing some actions
如果您因为重新格式化代码而感到失望,我认为这是一种更好的方法:
previous_category = 0
while True:
val = joystick.get_axis(1)
if 0.01 < val <= 0.25:
category = 1
#add 2 elif for the other categories, 2 and 3
if category == 1:
# performing some actions
elif category == 2:
# performing some actions
elif category == 3:
# performing some actions
#now that we've moved the object, we check if we need to print or not
if category != previous_category:
print_statement(category)
#and we update previous_category for the next round, which will just be the current category
previous_category = category
def print_statement(category):
#handle printing here based on type, this is more flexible
答案 1 :(得分:0)
您可以使用存储最后打印值的全局整数来完成此操作。像这样:
_last_count = None
def condprint(count):
global _last_count
if count != _last_count:
print('Waiting for joystick '+str(count))
_last_count = count