简体   繁体   中英

How to define a variable with a function?

I'm trying to make a program that turn characters into morse code and that also can decode it. But I've got stuck trying to define a variable from my function.

def func1(message):
    message = message
    print(message)

And then:

message = function('test)

And the output from this is that message is "None"

I want the "message" to get the output from the function.

Here my actual code:

def code(message):

    remove = ""

    message = message.lower()

    A = ".- "
    B = "-... "
    C = "-.-. "
    D = "-.. "
    E = ". "
    F = "..-. "
    G = "--. "
    H = ".... "
    I = ".. "
    J = ".--- "
    K = "-.- "
    L = ".-.. "
    M = "-- "
    N = "-. "
    O = "--- "
    P = ".--. "
    Q = "--.- "
    R = ".-. "
    S = "... "
    T = "- "
    U = "..- "
    V = "...- "
    W = ".-- "
    X = "-..- "
    Y = "-.-- "
    Z = "--.. "


    if "a" in message:
        message = message.replace("a", A)

    if "b" in message:
        message = message.replace("b", B)

    if "c" in message:
        message = message.replace("c", C)

    if "d" in message:
        message = message.replace("d", D)

    if "e" in message:
        message = message.replace("e", E)

    if "f" in message:
        message = message.replace("f", F)

    if "g" in message:
        message = message.replace("g", G)

    if "h" in message:
        message = message.replace("h", H)

    if "i" in message:
        message = message.replace("i", I)

    if "j" in message:
        message = message.replace("j", J)

    if "k" in message:
        message = message.replace("k", K)

    if "l" in message:
        message = message.replace("l", L)

    if "m" in message:
        message = message.replace("m", M)
    .........

And then:

if __name__ == "__main__":
    message = code("lol")
    print(message)
    print("\nDone!")

Output:

Morse Code: .-.. --- .-.. 
None

Done!

Variable message must be global. You can initialize it empty and use it inside you funtion like this:

global message = message.lower()

We don't see the end of your function, do you return something ? Is the end of your function like that :

return message

If your function don't return anything, you can't attribute it to a variable.

You could make a dict mapping of both coding,

>>> morse_to_key
{'---': 'O', '--.': 'G', '-...': 'B', '-..-': 'X', '.-.': 'R', '--.-': 'Q', '--..': 'Z', '.--': 'W', '.-': 'A', '..': 'I', '-.-.': 'C', '..-.': 'F', '-.--': 'Y', '-': 'T', '.': 'E', '.-..': 'L', '...': 'S', '..-': 'U', '-.-': 'K', '-..': 'D', '.---': 'J', '.--.': 'P', '--': 'M', '-.': 'N', '....': 'H', '...-': 'V'}
>>> key_to_morse
{'A': '.-', 'C': '-.-.', 'B': '-...', 'E': '.', 'D': '-..', 'G': '--.', 'F': '..-.', 'I': '..', 'H': '....', 'K': '-.-', 'J': '.---', 'M': '--', 'L': '.-..', 'O': '---', 'N': '-.', 'Q': '--.-', 'P': '.--.', 'S': '...', 'R': '.-.', 'U': '..-', 'T': '-', 'W': '.--', 'V': '...-', 'Y': '-.--', 'X': '-..-', 'Z': '--..'}
>>> morse_to_key = {v:k for k,v in key_to_morse.items()}
>>> morse_to_key
{'---': 'O', '--.': 'G', '-...': 'B', '-..-': 'X', '.-.': 'R', '--.-': 'Q', '--..': 'Z', '.--': 'W', '.-': 'A', '..': 'I', '-.-.': 'C', '..-.': 'F', '-.--': 'Y', '-': 'T', '.': 'E', '.-..': 'L', '...': 'S', '..-': 'U', '-.-': 'K', '-..': 'D', '.---': 'J', '.--.': 'P', '--': 'M', '-.': 'N', '....': 'H', '...-': 'V'}

And then,

>>> key_to_morse['a'.upper()]
'.-'
>>> morse_a = '.-'
>>> morse_to_key[morse_a]
'A'

With this, you could make your encoder and decoder,

>>> def code(msg):
...   return ' '.join(key_to_morse[c.upper()] for c in msg) # using space to distinguish when decoding easier :)
... 
>>> code('lol')
'.-.. --- .-..'
>>> def decode(msg):
...   return ''.join(morse_to_key[c] for c in msg.split(' ')).lower() # # using space to distinguish when decoding
... 
>>> decode('.-.. --- .-..')
'lol'

First, you want a simple dict that maps letters to their Morse code equivalent. Note that this table does not include a space:

morse_code = {
    "A": ".-",
    "B": "-...",
    # etc
}

Now your encode function should loop over the incoming message, one character at a time, and get the corresponding Morse code for that letter.

# Bad practice, but see below
def code(message):
    coded_message = ""
    for c in message:
        coded_message += morse_code[c]
    return coded_message

You also return the result, rather than printing it immediately, so that the caller can decide what to do with the result.

message = code("test")

The above implementation isn't very efficient, as repeatedly adding to the end of string requires you to constantly copy the previous value into the new value. Instead, you should use the join method

def code(message):
    return ["".join([morse_code[c] for c in message])]

which has the added benefit of making it much easier to add spaces to the output if you want, by using " " instead of "" as the separator string.

def code(message):
    return [" ".join([morse_code[c] for c in message])]

You should be making a list of your morse code strings, and then make a function that gets value x from a list of letters in the alphabet and converts it to value x from your morse code list. Make the for loop iterate through each letter of the string submitted in the function.

I tried with the below function, it is working fine for me.

def func1(message): message = message print(message) message = func1('test') Result: test.

and the main code you have posted you need have return message to see the result or print the message. below is the modified code,

` def code(message):

remove = ""

message = message.lower()

A = ".- "
B = "-... "
C = "-.-. "
D = "-.. "
E = ". "
F = "..-. "
G = "--. "
H = ".... "
I = ".. "
J = ".--- "
K = "-.- "
L = ".-.. "
M = "-- "
N = "-. "
O = "--- "
P = ".--. "
Q = "--.- "
R = ".-. "
S = "... "
T = "- "
U = "..- "
V = "...- "
W = ".-- "
X = "-..- "
Y = "-.-- "
Z = "--.. "


if "a" in message:
    message = message.replace("a", A)

if "b" in message:
    message = message.replace("b", B)

if "c" in message:
    message = message.replace("c", C)

if "d" in message:
    message = message.replace("d", D)

if "e" in message:
    message = message.replace("e", E)

if "f" in message:
    message = message.replace("f", F)

if "g" in message:
    message = message.replace("g", G)

if "h" in message:
    message = message.replace("h", H)

if "i" in message:
    message = message.replace("i", I)

if "j" in message:
    message = message.replace("j", J)

if "k" in message:
    message = message.replace("k", K)

if "l" in message:
    message = message.replace("l", L)

if "m" in message:
    message = message.replace("m", M)
print(message)

mes=code("hello") ` Result: .... . .-.. .-.. o

Please let me know if you still have any questions, i would be very happy to help you.

def code(message: str) -> str:
    mapping = {
        "A": ".-",
        "B": "-...",
        "C": "-.-.",
        "D": "-..",
        "E": ".",
        "F": "..-.",
        "G": "--.",
        "H": "....",
        "I": "..",
        "J": ".---",
        "K": "-.-",
        "L": ".-..",
        "M": "--",
        "N": "-.",
        "O": "---",
        "P": ".--.",
        "Q": "--.-",
        "R": ".-.",
        "S": "...",
        "T": "-",
        "U": "..-",
        "V": "...-",
        "W": ".--",
        "X": "-..-",
        "Y": "-.--",
        "Z": "--..",
    }

    return " ".join(mapping[i] for i in message.upper())


if __name__ == "__main__":
    message = code("lol")
    print(message)

Output

.-.. --- .-..

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