0

I have a simple try statement where i am assigning a variable to either x, o, or r (tic tac toe game i have made). The statements works if one of the three options is given, however, if it is something else given it says that it is returning a None object. I don't understand why it is not reassigning the variable to the new user input that is given on the second, third etc. run throughs

def chooseLetter(name):
    try:
        letter = input('Hello %s, would you like to be X or O or a random letter choice ("r") ' %name)
        assert letter.lower() == 'x' or letter.lower()== 'o' or letter.lower() == 'r'
        return letter
    except AssertionError:
        print('please choose either X or O ')
        chooseLetter(name)  
4
  • BTW, it's not good design to use assert to check data. assert is meant to check your program's internal logic, i.e., if you get an AssertionError that means there's something wrong with the code itself and it needs to be modified. For your case ValueError would be more suitable. Commented Feb 20, 2016 at 6:22
  • Also, recursion is best avoided in Python unless you're doing something that really needs it, eg processing recursive data structures, like trees. See if you can re-write your code to use a simple while loop. For more on this topic, please see Asking the user for input until they give a valid response. Commented Feb 20, 2016 at 6:22
  • @PM2Ring Processing a tree doesnt really need to be done with recursion, given their primitive nature :) You're still mostly right though, recursion is best reserved for recursive problems! Commented Feb 20, 2016 at 7:08
  • @user3697163: Fair enough; I guess it depends on what you're actually doing with the tree. :) FWIW, I've manipulated trees in ancient languages that don't support recursion, and I once wrote a non-recursive version of qsort (although I did "cheat" by maintaining my own stack). Commented Feb 20, 2016 at 7:21

1 Answer 1

2

The problem is that you don't return the value in the error case

def chooseLetter(name):
    try:
        letter = input('Hello %s, would you like to be X or O or a random letter choice ("r") ' %name)
        assert letter.lower() == 'x' or letter.lower()== 'o' or letter.lower() == 'r'
        return letter
    except AssertionError:
        print('please choose either X or O ')
        return chooseLetter(name)  
Sign up to request clarification or add additional context in comments.

1 Comment

This is right, as are the people above saying you shouldn't really be using asserts or recursion. I'd like to add that you could simply do assert letter.lower() in ('x','o','r') to be more concise though :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.