简体   繁体   English

如果无法在python中工作,则带有嵌套的For循环

[英]For loop with nested if not working in python

I'm writing a small morse code translator. 我正在写一个小型的摩尔斯电码翻译器。

But for some reason, it's not working. 但是由于某种原因,它不起作用。

For some reason, the broadcasting part is not working... I can't get it. 由于某些原因,广播部分无法正常工作...我听不到。 Any help is welcome ! 欢迎任何帮助!

Here is the code: 这是代码:

#import RPi.GPIO as GPIO
import re,time, pdb

def get_user_text():
    user_text = raw_input("Please enter the message you would lile to broadcast. >> ")
    user_text = user_text.lower()
    word_list = list(user_text)
    return word_list

def text_to_morse_code(alpha_text):
    morse_code = []
    for letter in alpha_text:
        if letter == "a" or letter == "à" or letter == "â" or letter == "ä":
            morse_code.append("01")
        if letter == "b":
            morse_code.append("1000")
        if letter == "c":
            morse_code.append("1010")
        if letter == "d":
            morse_code.append("100")
        if letter == "e" or letter == "è" or letter == "é" or letter == "ê":
            morse_code.append("0")
        if letter == "f":
            morse_code.append("0010")
        if letter == "g":
            morse_code.append("110")
        if letter == "h":
            morse_code.append("0000")
        if letter == "i" or letter == "î" or letter == "ï":
            morse_code.append("00")
        if letter == "j":
            morse_code.append("0111")
        if letter == "k":
            morse_code.append("101")
        if letter == "l":
            morse_code.append("0100")
        if letter == "m":
            morse_code.append("11")
        if letter == "n":
            morse_code.append("10")
        if letter == "o":
            morse_code.append("111")
        if letter == "p":
            morse_code.append("0110")
        if letter == "q":
            morse_code.append("1101")
        if letter == "r":
            morse_code.append("010")
        if letter == "s":
            morse_code.append("111")
        if letter == "t":
            morse_code.append("0")
        if letter == "u":
            morse_code.append("001")
        if letter == "v":
            morse_code.append("0001")
        if letter == "w":
            morse_code.append("011")
        if letter == "x":
            morse_code.append("1001")
        if letter == "y":
            morse_code.append("1011")
        if letter == "z":
            morse_code.append("1100")
        if letter == ".":
            morse_code.append("010101")
        if letter == " ":
            morse_code.append(" ")
        else:
            pass
    morse_code = ''.join(map(str, morse_code))
    morse_code = list(morse_code)
    return morse_code

def broadcast_code(code_to_broadcast, pin):

    # Set the board as BOARD
    #GPIO.setmode(GPIO.BOARD)
    print("Set the board to BOARD")

    # Setup the n th pin to OUTPUT
    #GPIO.setup(pin, GPIO.OUT)
    print("Set the "+str(pin)+"th to OUTPUT")

    # Starting the broadcast
    print("Starting Broadcast")
    start_broadcast = [0,1,0,1]

    for number in start_broadcast:
        if number == 1:
            #GPIO.output(pin,True)
            time.sleep(1)
            #GPIO.output(pin, False)
            print(number)
        if number == 0:
            #GPIO.output(pin,True)
            time.sleep(0.5)
            #GPIO.output(pin, False)
            print(number)

    print("Broadcasting")
    code_to_broadcast = code_to_broadcast
    for number in code_to_broadcast:
        if number == 1:
            #GPIO.output(pin,True)
            time.sleep(1)
            #GPIO.output(pin, False)
            print(number)
        if number == 0:
            #GPIO.output(pin,True)
            time.sleep(0.5)
            #GPIO.output(pin, False)
            print(number)

    #Boardcast end of transmission.
    print("Ending Boardcast")
    end_broadcast = [0,0,0,1,0,1]

    for number in end_broadcast:
        if number == 1:
            #GPIO.output(pin,True)
            time.sleep(1)
            #GPIO.output(pin, False)
            print(number)
        if number == 0:
            #GPIO.output(pin,True)
            time.sleep(0.5)
            #GPIO.output(pin, False)
            print(number)



    #GPIO.cleanup()
    print("Cleaned up the board.")

def get_code_broadcast():
    #
    #GPIO.output(pin,True)
    print("Hello")

if __name__ == '__main__':

    code = get_user_text()
    code = text_to_morse_code(code)
    broadcast_code(code,7)

And the output I get : 和我得到的输出:

$ Please enter the message you would lile to broadcast. >> Hello
Set the board to BOARD
Set the 7th to OUTPUT
Starting Broadcast
0
1
0
1
Broadcasting
Ending Boardcast
0
0
0
1
0
1
Cleaned up the board.

Example with dict: dict的示例:

morse_dict = {
    'a': '01',
    'b': '1000',
    'c': '1010',
}

def get_morse_code(text):
    morse_code = []
    for n in text:
        morse_code.append(morse_dict[n])
    return morse_code

And now you can do 现在你可以做

>>> print(get_morse_code('abcba'))

All you need to do is to expand the dict with all the morse stuff. 您需要做的就是用所有莫尔斯电文扩展字典。

Your question is about this loop: 您的问题与以下循环有关:

for number in code_to_broadcast:
    if number == 1:
        #GPIO.output(pin,True)
        time.sleep(1)
        #GPIO.output(pin, False)
        print(number)
    if number == 0:
        #GPIO.output(pin,True)
        time.sleep(0.5)
        #GPIO.output(pin, False)
        print(number)

The variable code_to_broadcase is a string. 变量code_to_broadcase是一个字符串。 This is the root of your problem. 这是问题的根源。

The string "0" is not equal to the integer 0 in Python. 在Python中,字符串"0"不等于整数0 Similarly, "1" is not equal to 1 . 类似地, "1"不等于1 Your code would work if you fixed the comparisons: 如果您固定了比较,则您的代码将起作用:

for number in code_to_broadcast:
    if number == "1":                  # test against a string
        #GPIO.output(pin,True)
        time.sleep(1)
        #GPIO.output(pin, False)
        print(number)
    if number == "0":                  # here too
        #GPIO.output(pin,True)
        time.sleep(0.5)
        #GPIO.output(pin, False)
        print(number)

Alternatively, you could probably change the string to a list of integers instead, and use your current loop code unmodified. 或者,您可以将字符串更改为整数列表,并使用当前未修改的循环代码。

Note that because the only difference between your two blocks is the amount of time you sleep for, you can simplify things by simply conditionalizing the amount of the delay: 请注意,由于两个块之间的唯一区别是睡眠时间,因此可以通过简单地限制延迟时间来简化事情:

for number in code_to_broadcast:
    #GPIO.output(pin,True)
    time.sleep(1 if number == "1" else 0.5)  # use a conditional expression
    #GPIO.output(pin, False)
    print(number)

There are a number of other places your code could be improved (mostly by factoring out repeated coded). 您的代码还有很多其他地方可以改进(主要是通过排除重复编码)。 I'd strongly suggest using a dictionary to store the translation between letters and morse code dits and dahs, rather than using a very long series of if statements. 我强烈建议使用字典来存储字母和莫尔斯电码的字母和字母之间的翻译,而不要使用很长的if语句系列。 (If you do keep the if chain, all of the if s after the first should probably be elif s, since they'll only be true if none of the previous ones were. Using elif will let Python stop testing the later conditions if an earlier one was True .) (如果您确实保留了if链, if第一个之后的所有if可能都应该是elif ,因为只有在先前的条件都不存在的情况下它们才为true。使用elif可以让Python停止测试后面的条件,如果较早的是True 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM