A newbie's non-blender-related python question


(rivenwanderer) #1

I’m just starting to learn python in general, from the free “How to think like a computer scientist” book. I have a question: Why does it work when I do this:

given = int(raw_input("Type a number. "))
def numberchecker(n):
    if n >= 10:
        print n
    else:
        n=10
        numberchecker(n)
numberchecker(given)

{that is, it takes the inputted number and spits it back out unless it’s smaller than 10, in which case it spits back 10}

but then this other way prints “none” for inputted numbers less than 10 {but works for numbers greater than 10}

given = int(raw_input("Type a number. "))
def numberchecker(n):
    if n == 10:
        return n
    else:
        n=10
        numberchecker(n)
print numberchecker(given)

Anybody know? I haven’t been able to figure out why it doesn’t work–is it a dumb mistake, an eccentricity of python, or something fundamentally wrong with what I’m doing?


(theeth) #2

there is a very big difference between the two. In the first one, the print function is done inside the numberchecker function, which means that numberchecker(***) will always print something. In the second one, print is used on the output of the numberchecker function and that’s where the problem is. Follow your code with a value, and you will see that the function doesn’t return anything if the number is higher than 10. You could solve it with one of these two ways:

given = int(raw_input("Type a number. ")) 
def numberchecker(n): 
    if n == 10: 
        return n
    else: 
        n=10 
        print numberchecker(n) 
print numberchecker(given)

or

given = int(raw_input("Type a number. ")) 
def numberchecker(n): 
    if n == 10: 
        print n
    else: 
        n=10 
        numberchecker(n) 
numberchecker(given)

I hope that was somewhat clear.

Martin