Search code examples
pythonraspberry-piuser-inputled

Python getting user input and comparing input to string


I'm writing a program where the user can choose a color and have an LED of said color light up using a Raspberry Pi. After accepting user input and trying to compare it to a color, I get "NameError: name 'red' is not defined". How can I fix this?

Here is my code:

import RPi.GPIO as GPIO
import time

GPIO.setwarnings(False)

#use raspberry pi board numbers
GPIO.setmode(GPIO.BOARD)  

#GPIO output channel
GPIO.setup(7, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(32, GPIO.OUT)
GPIO.setup(37, GPIO.OUT)
GPIO.setup(40, GPIO.OUT)
GPIO.setup(33, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)

#get led color
ledColorList = input("What color of light do you want to turn on? Red, green, blue, yellow, or all").split(' ')

#blink function
def blink(pin):
    GPIO.output(pin,1)
    time.sleep(.25)
    GPIO.output(pin,0)
    time.sleep(.25)
    return

if ledColorList[0] == RED:
    blink(7)  

#turn off all pins
GPIO.cleanup()

Solution

  • I think you'd be a little better off forcing the input into lower case and taking it in through raw_input:

    ledColorList = raw_input("What color of light do you want to turn on? Red, green, blue, yellow, or all").lower().split(' ')
    

    then checking it against

    if ledColorList[0] == "red":
        blink(7)