Scott Chagall
Scott Chagall

Reputation: 85

Python script does not update a variable

I'm trying to make a Raspberry Pi (model B+) switch on a user chosen LED via GPIO by means of an io.output() function. However I have trouble getting my script to do so. The script is written in Python3.

# Set GPIO pins for each color
red = 11
yellow = 9
green = 10
# etc...

# LEDs are set as output
io.setup(red, io.OUT)
io.setup(yellow, io.OUT)
io.setup(green, io.OUT)
# etc...

# Function
def phase(color):
    io.output(color, io.HIGH)

color = input("Please choose a color like red, yellow, green, ...: ")

What I try to achieve is this: based on the choice the user makes, that particular LED is switched on.

The user has a choice of 10 colors.

I know this can be achieved by setting:

if color == 'red':
    io.output(red, io.HIGH)
elif color == 'yellow':
    io.output(yellow, io.HIGH)
elif color == 'green':
    io.output(green, io.HIGH)
#etc...

But I would like to only have 1 line of code in which the variable color is updated according to what color the user has chosen:

io.output(color, io.HIGH)

It seems that setting variables in Python3 works a little different then I thought (I'm used to PHP and not that experienced in Python3 yet).

I would expect the variable color to be processed by Python into the users input (let's say "red"), which should subsequently by processed into the corresponding GPIO pin number which is 11.

However that doesn't take place and I can't figure out why. I keep getting errors telling me that color should be an integer. And I thought variables in this case worked like color = red = 11.

How do I pass a variable in my io.output() function? Is that possible or am I stuck with having to write a line of code for each color LED? That seems very redundant to me but maybe I'm completely wrong here.

Upvotes: 1

Views: 183

Answers (2)

furas
furas

Reputation: 142631

You can use dictionary to convert string to integer

all_colors = {
    "red": 11,
    "yellow": 9,
    "green": 10
}

color = input("Please choose a color like red, yellow, green, ...: ")
color = color.lower().strip()

if color in all_colors:
    value = all_colors[color]
    io.output( value, io.HIGH )
else:
    print("unknown color")

Upvotes: 1

Ouroborus
Ouroborus

Reputation: 16865

Your variable color contains a string. You appear to want some way to map that string to an integer. A dictionary (dict) would be perfect for that and allow some other optimizations as well:

# Set GPIO pins for each color
colors = {
    'red': 11,
    'yellow': 9,
    'green': 10,
    # etc...
}

# LEDs are set as output
[io.setup(v, io.OUT) for k,v in colors]

# Function
def phase(color):
    io.output(colors[color], io.HIGH)

color = input("Please choose red, yellow or green: ")
phase(color)

Upvotes: 1

Related Questions