1

I'm trying to complete a python Hangman miniproject to help me learn to code.

I've created a function that will hopefully ask the player for a letter, check the letter is only 1 letter and make sure it is not a number.

Here is the code I have so far:

def getLetter():
    letter = raw_input('Please enter a letter...')

    if letter.isdigit() == True:
        print('That is a number!')
        getLetter()

    if len(str(letter)) >1:
        print("Sorry, you have to enter exactly ONE letter")
        getLetter()

    else:
        return letter

This works fine when the first input is correct, ie. one letter. However, when the input is incorrect, e.g 'ddddd', the program asks for another letter to be input but will either return the initial input ('ddddd') rather than the new input, or return nothing at all.

How can I make it return the new input? Do I need to clear the raw_input? If so, how?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
HereItIs
  • 145
  • 1
  • 4
  • 15
  • 1
    Recursion is not the best way for validating input. Never underestimate the power of a user to break your program, in this case entering invalid input so many times that you hit the max recursion depth. A loop is a much better option for validating inputs. – DeepSpace Jul 25 '16 at 12:06
  • 1
    The recursion feels so wrong, it is confusing to follow in your example, I think a loop is a better option. Oh you are forgetting the `return` – John Doe Jul 25 '16 at 12:09
  • 1
    Adding on to John Doe, if you are going to use your code above add the `return` inside your if statement to make it `return getLetter()` – Newyork167 Jul 25 '16 at 12:14

2 Answers2

4

You are not returning the result of your recursive calls; everywhere you call getLetter() you drop the return value.

Add return before those calls to pass on the result up the call chain:

return getLetter()

However, you should not be using recursion at all; use a loop instead:

def getLetter():
    while True:
        letter = raw_input('Please enter a letter...')

        if letter.isdigit() == True:
            print('That is a number!')
            continue

        if len(str(letter)) >1:
            print("Sorry, you have to enter exactly ONE letter")
            continue

        return letter

Every recursive call adds onto the call stack, which is not unlimited in size; eventually a user always entering numbers will break your program! See Asking the user for input until they give a valid response for more information.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0
def get_valid_letter():    
    while True:

        letter = raw_input('Please enter a letter...')
        if letter.isdigit() == True:
            print('That is a number!')

        elif len(str(letter)) >1:
            print("Sorry, you have to enter exactly ONE letter")

        else:
            return letter
John Doe
  • 1,364
  • 1
  • 12
  • 19