Because of character = get_char()
, your loop only runs once, because it will recurse deeper if it fails instead of iterating again. This probably isn't what you want, because it's slower and runs the risk of overflowing the stack. The cleanest way to do this would probably be (you could replace my messages with yours easily):
def get_char(is_valid = lambda c: True):
while True:
c = raw_input('enter a character > ')
if is_valid(c):
keep = raw_input('do you want to use {0}? (Y/N)> '.format(c)).lower()
if 'n' in keep:
continue # go back to While True line
return c
print('{0} is not a valid character'.format(c))
Session:
>>> get_char()
enter a character > a
do you want to use a? (Y/N)> n
enter a character > c
do you want to use c? (Y/N)> no
enter a character > x
do you want to use x? (Y/N)> y
'x'
At least, this is the cleanest in my opinion. Your implementation has a few other problems, like proceed in "N,n"
, which would also count comma as an n
, and if the character isn't isalpha
, you still return it.