摩尔斯电码python3:不是对用户可以输入的每个单词使用多个if语句,而是如何对此进行循环?

2024-09-30 00:29:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个树莓皮莫尔斯电码程序:
如何简化if语句:我想让程序播放用户键入的任何内容,但我不知道如何使用多个if语句。救命啊!! 我希望该程序能够发挥任何字的用户键入,但我不知道如何做到这一点。如果我需要给每个letgter分配一个变量,我该怎么做?你知道吗

import RPi.GPIO as GPIO

from time import sleep


LED_GPIO = 4

print("Getting ready...")

GPIO.setmode(GPIO.BCM)

GPIO.setup(LED_GPIO, GPIO.OUT)



def lighton(timeon):

    print ("Light On - " , timeon)

    GPIO.output(LED_GPIO, True)
    sleep(timeon)
    GPIO.output(LED_GPIO, False)
    sleep(timeoff)



dashtime = .5
dottime = .25
timeoff = .1

x = 1 

while x > 0:

    let = input("Enter a letter or * to quit")

    if let == "*":
        x=0

    elif let == "s":       
        lighton(dottime)    
        lighton(dottime) 
        lighton(dottime)

    elif let == "o":
        lighton(dashtime)
        lighton(dashtime)
        lighton(dashtime)

    elif let == "sos":

        lighton(s)

        lighton(dashtime)
        lighton(dashtime)
        lighton(dashtime)       

        lighton(dottime)    
        lighton(dottime) 
        lighton(dottime)        

    else: print ("Letter not recognized - try again")


GPIO.cleanup()

print("Bye Bye")   

Tags: 用户程序ledgpio键入ifsleep语句
1条回答
网友
1楼 · 发布于 2024-09-30 00:29:19

使用字典来查找每个字符的flash模式,而不是if。你可以通过两个步骤来完成,一个是将一个字母转换成莫尔斯电码的dict,另一个是知道如何将其转换成闪光长度的dict。你知道吗

import RPi.GPIO as GPIO    
from time import sleep

print("Getting ready...")

LED_GPIO = 4
GPIO.setmode(GPIO.BCM)    
GPIO.setup(LED_GPIO, GPIO.OUT)

def lighton(timeon):    
    print ("Light On - " , timeon)    
    GPIO.output(LED_GPIO, True)
    sleep(timeon)
    GPIO.output(LED_GPIO, False)
    sleep(timeoff)

# light on/off times
dashtime = .5
dottime = .25
timeoff = .1

# ascii to morse translation
morse_letters = { "S":"...", "O":" -" } # fill in the rest!

# morse to time translation
morse_to_time = { ".":dottime, "-":dashtime }

while True:
    # get a line from the user... and uppercase because morse
    # doesn't do lower
    text = input("Enter text or * to quit").uuper()
    if text == "*":
        break
    # step through each character in text 
    for character in text:
        # get the morse pattern for the character then flash
        # the light for each dash or dot
        for dashdot in morse_letters.get(character, ""):
            lighton(morse_to_time[dashdot])

GPIO.cleanup()

print("Bye Bye")   

相关问题 更多 >

    热门问题