Playing the 'Guess my number' game recursively
Thursday, 14. June 2007, 12:08:46
Most programmers have written their own version of the 'Guess my number' game -- You know, it picks a number, you guess, it says if you're too high or too low, that kind of thing.
What we usually do is this :
def guess(n) :
while True :
x = int(raw_input('Enter a number : '))
if x < n :
print 'You're too low.'
if x > n :
print 'You're too high.'
if x == n :
print 'You're absolutely right.'
return
I'd never realized that it could be done recursively, although it looks pretty obvious. No, it doesn't offer any performance boosts, and no, it doesn't make it easier to read. It's just something different.
def guess(n) :
x = int(raw_input('Enter a number : '))
if x < n :
print 'You're too low.'
guess(n)
return
if x > n :
print 'You're too high.'
guess(n)
return
if x == n :
print 'You're absolutely right.'
return
The usefulness of recursion is not perhaps as apparrent in this case as it usually is, but still...















Mick-E # 14. June 2007, 16:37
Anonymous # 1. September 2008, 02:39
swerewd