Home > other >  Why is my code returning a second "matches None" line?
Why is my code returning a second "matches None" line?

Time:09-09

I have to create a function in Python that matches keypad letters with their corresponding number(excluding 1 & 0). When I run my code and input a letter, I get the correct match, but I also get a (letter,"matches",None) line below it. What am I doing wrong and what do I need to fix to make sure that the None line doesn't occur? Code:

def keypad(ch):
    if ch == "A" or ch == "a" or ch == "B" or ch == "b" or ch == "C" or ch == "c":
        print(ch,"matches",2)
    elif ch == "D" or ch == "d" or ch == "E" or ch == "e" or ch == "F" or ch == "f":
        print(ch,"matches",3)

s = str(input("Enter a letter:"))
print(s,"matches",keypad(s))

Sample output for this:

Enter a letter:D
D matches 3
D matches None

CodePudding user response:

Your keypad function calls print, which is the first output line you see. Since its doesn't explicitly return anything, it implicitly returns None, which you then print in the last line of code.

In short, remove the print from your last call:

s = str(input("Enter a letter:"))
keypad(s)

CodePudding user response:

Your function is not returning anything, so it implicitly returns None.

You are printing in the function, thus the print of 'D matches 3'.

You are printing outside of the function, thus the print of 'D matches None'.

CodePudding user response:

You're printing the return value of the call to keypad(s), which itself prints the first line. Don't print the return value, but just call the function with keypad(s), or have the function return what needs to be printed and don't have it print anything itself.

So, either:

def keypad(ch):
    if ch == "A" or ch == "a" or ch == "B" or ch == "b" or ch == "C" or ch == "c":
        print(ch,"matches",2)
    elif ch == "D" or ch == "d" or ch == "E" or ch == "e" or ch == "F" or ch == "f":
        print(ch,"matches",3)

s = str(input("Enter a letter:"))
keypad(s)

Or:

def keypad(ch):
    if ch == "A" or ch == "a" or ch == "B" or ch == "b" or ch == "C" or ch == "c":
        return 2
    elif ch == "D" or ch == "d" or ch == "E" or ch == "e" or ch == "F" or ch == "f":
        return 3

s = str(input("Enter a letter:"))
print(s, "matches", keypad(s))

Better yet:

def keypad(ch):
    return 2 if ch.lower() in 'abc' else 3 if ch.lower() in 'def' else None


s = str(input("Enter a letter:"))
print(s, "matches", keypad(s))

Note that the first and second solution are different when you enter anything other than 'a' through 'f'. If you don't want to print anything in that case, the first solution is the best, and this is the short version of that:

def keypad(ch):
    result = 2 if ch.lower() in 'abc' else 3 if ch.lower() in 'def' else None
    if result is not None:
        print(s, "matches", result)


s = str(input("Enter a letter:"))
keypad(s)
  • Related