[英]Python: why doesn't if(a == 0): a = 1 if(a == 1): a = 0 work for making a toggle
I'm working on a project using python to read the digital inputs on the raspberry pi. 我正在使用python读取树莓派上的数字输入的项目。 I wanted to turn one of the buttons into a toggle, as in it switches a value between 1 and 0 whenever I press it.
我想将其中一个按钮变成一个切换,因为每当我按下它时,它就会在1到0之间切换一个值。 Everything is working fine except the section:
除以下部分外,其他一切正常:
if(a == 0.0):
a = 1.0
if(a == 1.0):
a = 0.0
It seems like this should work with the rest of the code to make the value toggle between 1 and 0 whenever the button is pressed, but a prints as 0.0 every time, does anyone know why this is? 似乎这应该与其余代码一起使用,以便每当按下按钮时使值在1和0之间切换,但是每次打印为0.0,有人知道为什么吗?
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)
a = 0.0
b = 0.0
c = 0
while True:
if(GPIO.input(4) ==1 and c ==0):
print 'Button 1 Pressed'
if(a == 0.0):
a = 1.0
if(a == 1.0):
a = 0.0
c = 1
print a
if(GPIO.input(4) !=1):
c = 0
if(GPIO.input(24) ==0):
print 'Button 2 Pressed'
If you start with a = 0
, both if
statements match, and you end up back at 0
. 如果以
a = 0
开头,则两个 if
语句都匹配,最后以0
结束。
Use if .. elif
instead; 使用
if .. elif
代替; this is one statement and only one of the branches can ever match: 这是一条语句,只有一个分支可以匹配:
if a == 0.0:
a = 1.0
elif a == 1.0:
a = 0.0
I'm not sure what you are using these values for, however. 但是,我不确定您将这些值用于什么。 Floating point comparisons are tricky, because calculations with floats can lead to very subtle differences , where it may look like you have
1.0
exactly but you really have 0.9999999999999872545
. 浮点数比较比较棘手,因为使用浮点数进行计算可能会导致非常细微的差异 ,在这种情况下,您看起来确实像是
1.0
但实际上确实是0.9999999999999872545
。 That'll not be equal to 1.0
. 那不等于
1.0
。 Perhaps you wanted to use a boolean instead? 也许您想使用布尔值代替? In that case use:
在这种情况下,请使用:
a = False
# toggle
a = not a
If you do need to use floats, test if your value is close enough : 如果确实需要使用浮点数,请测试您的值是否足够接近 :
if abs(a - 0.0) < 1e-9:
a = 1.0
elif abs(a - 1.0) < 1e-9:
a = 0.0
If you are using Python 3.5 or newer, you can use the new math.isclose()
function : 如果您使用的是Python 3.5或更高版本,则可以使用新的
math.isclose()
函数 :
from math import isclose
if isclose(a, 0.0):
a = 1.0
elif isclose(a, 1.0):
a = 0.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.