Skip to main content
 首页 » 编程设计

Python 3.6 字符串输入

2025年05月04日13tintown

我正在使用 Raspberry Pi 3 并使用 Python 控制三个 LED。 我可以说我擅长 Python。这是我的代码:

import RPi.GPIO as GPIO 
import time 
 
#GPIO Pins 
GPIO.setmode(GPIO.BCM) 
GPIO.setwarnings(False) 
GPIO.setup(17,GPIO.OUT) 
GPIO.setup(27,GPIO.OUT) 
GPIO.setup(22,GPIO.OUT) 
 
def led(color,state): 
    if state == "on": 
        if color == "g": #green 
            GPIO.output(27,GPIO.HIGH) 
        elif color == "y": #yellow 
            GPIO.output(22,GPIO.HIGH) 
        elif color == "r": #red 
            GPIO.output(17,GPIO.HIGH) 
        print ("LED on") 
    elif state == "off": 
        if color == "g": 
            GPIO.output(27,GPIO.LOW) 
        elif color == "y": 
            GPIO.output(22,GPIO.LOW) 
        elif color == "r": 
            GPIO.output(17,GPIO.LOW) 
        print ("LED off") 
 
while True: 
    leds_col = input("Color (r, g, y): ") 
    leds_stat = input("On or Off: ") 
    led(leds_col, leds_stat) 

我有一个名为 led() 的函数,它接受两个参数,color(g、y 或 r)和 state(on 或离开)。在 while 循环中,leds_col 询问控制台中的颜色,leds_stat 询问状态。 现在我想要实现的是将它们结合起来,而不是要求不同行中的颜色和另一行中的 LED 状态。因此,例如我会在控制台上写:

g, on 

它会点亮绿色 LED。 我知道我可以使用 if 语句,例如: 如果 led_input == "g, on": GPIO.output(27,GPIO.HIGH) 但我确信有更好的方法来做到这一点。

请您参考如下方法:

使用string.split() :

while True:  
    what = input("Color [r,g,y] and state [on,off] (ex.: 'r on'): ").strip().lower().split() 
    if len(what)==2: 
        leds_col,leds_stat = what 
        # sort the color input to reduce possible values 
        leds_col = ''.join(sorted(leds_col)) 
        if leds_col not in "r g y gr ry gy gry" or leds_stat not in "on off": 
            continue 
    else: 
        continue 
    led(leds_col, leds_stat) 

如果输入无效,这将继续询问直到输入有效。 参见 Asking the user for input until they give a valid response有关输入验证的更多想法。


不相关 - 但您可以优化您的 led 功能:

def led(color,state): 
    d = {"on":GPIO.HIGH, "off":GPIO.LOW, 
         "g":27, "y":22, "r":17} 
 
    for c in color: 
        GPIO.output(d[c],d[state]) 
    print("LED",color,state) 

通过使用查找字典:参见 dict()