Function not returning correct value - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Function not returning correct value (/thread-15279.html) |
Function not returning correct value - ActualNoob - Jan-10-2019 So I am an absolute beginner. And I can't unserstand why a=letter_value(message) makes a a zero. def letter_value(letter):
RE: Function not returning correct value - stullis - Jan-10-2019 Please use the https://python-forum.io/misc.php?action=help&hid=25 when posting code. The code tag doesn't work here. The code looks fine. What is your input value? Here's a quick rewrite of your code with a few small changes. def letter_value(letter): letter = letter.lower() if letter == "a": l_value = 0 elif letter == "b": l_value = 1 elif letter == "c": l_value = 2 elif letter == "d": l_value = 3 elif letter == "e": l_value = 4 elif letter == "f": l_value = 5 elif letter == "g": l_value = 6 elif letter == "h": l_value = 7 elif letter == "i": l_value = 8 elif letter == "j": l_value = 9 elif letter == "k": l_value = 10 else: l_value = -1 return l_value while True: message = input("Enter message") a = letter_value(message) print(letter_value(message)) print(a) RE: Function not returning correct value - scidam - Jan-10-2019 The power of Python programming language is that you can rewrite the function above in two lines of code: def letter_value(letter): return {v: i for i, v in enumerate('abcdefghijk')}.get(letter.lower(), -1) RE: Function not returning correct value - stullis - Jan-11-2019 Or, in this case: def letter_value(letter): return "abcdefghijklmnopqrstuvwxyz".index(letter) |