2015-12-28 189 views
0

我正在編寫一個程序,用戶可以選擇一種顏色並使用Raspberry Pi將所述顏色的LED點亮。接受用戶輸入並嘗試將其與顏色進行比較後,我得到「NameError:name'紅色'未定義」。我怎樣才能解決這個問題?Python獲取用戶輸入並將輸入與字符串進行比較

這裏是我的代碼:

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() 
+1

這是不是海峽的比較如果ledColorList [0] == RED不要忘記「」它應該是這樣的:如果ledColorList [0] ==「紅色」 – miguels

回答

1

我想你最好有點偏離迫使輸入小寫和服用的raw_input通過:

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

然後檢查其對

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

謝謝,這使得它按預期工作。由於我是python的新手,你可以解釋一下,如果這是大寫還是使用輸入而不是raw_input會導致失敗? – kalenpw

+0

你的問題在回溯中有小寫「紅色」,表示你有兩個問題:1)沒有稱爲「red」的變量,只有一個稱爲「RED」2)通過使用raw_input()解決此問題不會解決字符串比較的案例問題。 –

0

RED是一個字符串litteral:應該在引號之間放。

+0

我已經修復它,現在它運行,但燈不眨。任何想法爲什麼會這樣? – kalenpw

0

爲Python 2.x中,您可以使用raw_input()代替input()因爲

In Python 2.x, input() expects a Python expression, which means that if you type red it interprets that as a variable named red. If you typed "red", then it would be fine.

相關問題