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)  
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 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. – PM 2Ring Feb 20 '16 at 06: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](http://stackoverflow.com/q/23294658/4014959). – PM 2Ring Feb 20 '16 at 06: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! – DaveBensonPhillips Feb 20 '16 at 07: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). – PM 2Ring Feb 20 '16 at 07:21

1 Answers1

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)  
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 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 :) – DaveBensonPhillips Feb 20 '16 at 07:10