First, use raw_input instead of input , and then convert it to an integer. To answer your question, ask the user to enter this:
play_again = raw_input('Play again? (y/n)') if play_again.lower().startswith('y'): add() return
input is unsafe because it is evaluated as native code, and therefore a qualified person can crack the system. raw_input treats the input as a string, and you can call int() on the result.
This only applies to Python 2. For Python 3, input fine - it replaced Python 2 with raw_input .
In addition, there is recursion in the function - although no one is likely to be persistent enough to overflow the stack, although for other applications iteration will be the best method.
Converting this to an iterative loop is trivial (and also recommended). Put everything separately from the import inside the while True . Then at the end of the loop add this code:
play_again = raw_input('Play again? (y/n)') if play_again.lower().startswith('y'): continue break
Of course, you can check 'n' instead of 'y' and get rid of continue by replacing it with a simple break statement.
Note that you can also replace the if with a less readable one:
if raw_input('Play again? (y/n)').lower().startswith('y'):
And get rid of the intermediate variable play_again . Although I would not sacrifice readability for compactness.
source share