0

Good day,

I have started playing around with python and after making some scripts (dice generate, madlibs, hangman) I am trying to a battleship script.

I realise this coding might not be the most efficient way to code, but my current goal is the get it working with the limited understanding I have.

For part of the script I have function to take care of guesses the player make.

def turn():
    board = ['A', 'B', 'C']
    guess = input('Enter the target coordinate: ')
    try:  
        if guess[:1].upper() in board and int(guess[1:]) in range(1,11): 
            guess = guess.upper()
            print('Targeting %s!' % (guess))
            return guess
        elif guess == 'quit': quit
        else: 
            print('Please enter a proper coordinate using A thru J and 1 thru 10.') 
            turn()
    except: 
        print('Please enter a proper coordinate using A thru J and 1 thru 10.')
        turn()
    print(turn())

If I enter 'a2' I get the following

Targeting A2!
A2

which matches what I expect

When I enter a wrong input 'bla' or 'a13' I get prompted for a new input. All is going as expect so far, but when I now enter a correct input 'a2' I get the following

Targeting A2!
None

I can't grasp why 'return guess' works properly when I enter a good input right away, but not when I entered a bad input first.

Hopefully one of you can clarify this for me.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
Gobbledy
  • 3
  • 2
  • 1
    ignoring the quality of the code, your issue is in your exception, you need to `return turn()` – Nullman May 14 '19 at 11:55

1 Answers1

4

You need to return the result of your recursive calls, otherwise they will be implicitly None.

Note: every method / function in Python has a return value. If you do not set it explicitely, it defaults to None.

def turn():
    board = ['A', 'B', 'C']
    guess = input('Enter the target coordinate: ')
    try:  
        if guess[:1].upper() in board and int(guess[1:]) in range(1,11): 
            guess = guess.upper()
            print('Targeting %s!' % (guess))
            return guess
        elif guess == 'quit': 
            quit
        else: 
            print('Please enter a proper coordinate using A thru J and 1 thru 10.') 
            return turn() # return the result of the recursive call
    except: 
        print('Please enter a proper coordinate using A thru J and 1 thru 10.')
        return turn() # return the result of the recursive call
print(turn())
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
  • Thanks for clarification. I assumed the return inside the 'if' statement would always be the last step with a correct answer. – Gobbledy May 14 '19 at 17:34