Raspberry Pi lights the wrong led

-3

I'm doing an experiment in which I light a green led or a red led according to the result of a question. I'm sure the problem is not the circuits, because I've tried in several ways and it always happens the same: the led that is lit is always red. Here is the code I used:

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
def led(pin):
    GPIO.output(pin,GPIO.HIGH)
    time.sleep(3)
    GPIO.output(pin,GPIO.LOW)
GPIO.setup(12,GPIO.OUT)
GPIO.setup(16,GPIO.OUT)
print "How much is 2+2?"
awnser=raw_input(" >")
if awnser==4:
    led(16)
else:
    led(12)
GPIO.cleanup()

Can anyone help me? Thank you.

    
asked by anonymous 19.12.2018 / 19:33

1 answer

3
awnser=raw_input(" >")
if awnser==4:
    led(16)
else:
    led(12)

The condition awnser==4 will never be satisfied, since the function raw_input always returns a string and Python differentiates '4' from 4 .

You will then need to convert the value to integer before comparing it:

awnser = int(raw_input('> '))

Just be careful that a ValueError ception will be thrown if the value entered by the user can not be converted to an integer, such as a letter, for example.

    
19.12.2018 / 20:04