简体   繁体   中英

lower() function not converting input to lowercase in python 3 script for Raspberry Pi

I have an RGB LED connected to a Raspberry Pi 3 with the below code. What I want to do is present the user with a question to choose Red, Green or Blue, corresponding to a variable linked to specific GPIO pins.

When user enters, Red, the LED will turn red. When they enter Blue, the LED will turn blue.

Currently if I enter red, the code will print '20' (integer), which corresponds to the BCM pin 20. This is good, but my problem is that I'm having trouble converting the user's string response to lowercase first. (ie, convert RED to red) .

I am getting an error:

request =  input("Choose a color. Red/Green/Blue".lower())
File "<string>", line 1, in <module>
NameError: name 'Red' is not defined

The code below is at its simplest form to first test that I can get the lowercase input from the user.

red = 20
green = 16
blue = 21

try:
    while True:
        # I would like to convert user's answer (Red, Green,Blue) to a lowercase answer (ie. red, green blue)
        request =  input("Choose a color. Red/Green/Blue").lower()

        print(type(request))
        print(request)

except KeyboardInterrupt:

Any help would be much appreciated.

This is not Python3. Python's 3 "input" would return you a string, which you could then convert to lowercase - but your code does not have anything in it for, given a string with the color name, retrieve the cotnents associated with the variable with that same name.

Python 2's input, on the other hand, performs an eval , running whatever the user types in as a Python expression, before returning the result. Therefore, when the user types in red it will give you theassociated value 20 . (And a lower call on this value would fail).

What you have to do there is: Write code that will work in Python2 or Python3, and second, make a consistent mechanism to retrieve your color given a user-typed string. For this last part, the recomended way is to associate your color names and values using a dictionary mapping, rather than outright as variables.

So:

try:
   input = raw_input 
except NameError: 
   pass

colors = dict(
    red = 20,
    green = 16,
    blue = 21,
)

try:
    while True:
        request =  input("Choose a color. Red/Green/Blue")
        color = colors[request.lower()]
        ...
    except NameError:
        print("Invalid color name selected")
    except KeyboardInterrupt:
        ...

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