Python Forum
create function let_to_num() - 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: create function let_to_num() (/thread-25989.html)



create function let_to_num() - al_Czervik - Apr-17-2020

In my assignment I have to convert a number to letter using a list. I've been able to do this except I'm stuck on the bonus question. When the input is left blank, the index needs to refer to [2]. I've tried to add an elif statement, but I continue to get the first index no matter what I do. The course has not covered any information on handling blank input entries. My code is as follows:
phone_letters = [' ', '','ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXYZ']
letter = input('Enter a single letter, space or empty: ')

def let_to_num(letter):
    key = 0
    while key < 10:
        if letter.upper() in phone_letters[key]:
            return key
        elif letter == False: #don't know how to deal with a blank input
            key = 1
        else:
            key = key + 1           
    return "Not Found"

print(letter,"=",let_to_num(letter))



RE: create function let_to_num() - bowlofred - Apr-17-2020

The input isn't your problem, it's how you're checking. You probably want to just put a special case of checking for your input being "" at the beginning of the function.

The problem is that you're seeing if the letter is located in the values of phone_letters, but an empty string will always match that test. So your check looks for it in key=0 and "finds" it.

>>> "x" in "foobar"  # not present
False
>>> "" in "foobar"   # empty string always present
True
So you need to check for input == "" early and deal with that. Then do your loop (or whatever).

if letter == "":
    return 2
.....

Note that this is an excellent use for a dictionary. If you create a dictionary with the number of each of the letters you want, then looking it up and returning that value is easy. It also handles the empty string without a special case.

>>> let_to_num = {"": 2,
... " ": 1,
... "A":3,
... "B":3,
... "C":3,
... "D":4}
>>> let_to_num.get("", "Not Found")  # empty string
2
>>> let_to_num.get(" ", "Not Found")  # space
1
>>> let_to_num.get("D", "Not Found")  # regular letter
4
>>> let_to_num.get("$", "Not Found")  # invalid letter
'Not Found'



RE: create function let_to_num() - al_Czervik - Apr-17-2020

Thanks!