A fairly general way to do this is to use the while True , which will run indefinitely, with break statements to exit the loop when the input is valid:
print "pick a number, 1 or 2" while True: a = int(raw_input("> ") if a == 1: print "this" break if a == 2: print "that" break print "you have made an invalid choice, try again."
There is also a good way to limit the number of attempts, for example:
print "pick a number, 1 or 2" for retry in range(5): a = int(raw_input("> ") if a == 1: print "this" break if a == 2: print "that" break print "you have made an invalid choice, try again." else: print "you keep making invalid choices, exiting." sys.exit(1)
source share