简体   繁体   中英

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. 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. 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?

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 .

Use if .. elif instead; 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 . That'll not be equal to 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 :

from math import isclose

if isclose(a, 0.0):
    a = 1.0
elif isclose(a, 1.0):
    a = 0.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM