Newbie question about function return values

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Thu Mar 13 19:50:56 EST 2003


> From: Brian Munroe [mailto:bmunroe at tribador.nu]
> 
> Ok, so it is late in the day and I, for the life of me, 
> cannot figure out
> what is going on in the code below.
> 
> I should get the value of x, but instead I am getting 'None' (in
> sectors(500))
> 
> So then I create another function, and I get the correct value for the
> return value (in hello(2))
> 
> #!/usr/bin/python
> 
> def sectors(x):
>     if ((x % 512) != 0):
>         x = x + 1
>         sectors(x)
          ^^^^^^^^^^
>     else:
>         return x
> 
> def hello(x):
>     x = x * x
>     return x

You should take some inputs and work through the code line by line. At some point you will see that you are not always returning a value from `sectors`. When you exit a function without explicitly returning anything it returns `None`.

I'm not going to correct the inefficiencies in the code - that's your job.

def sectors(x):
    if ((x % 512) != 0):
        x = x + 1
        return sectors(x)
    else:
        return x

def hello(x):
    x = x * x
    return x





More information about the Python-list mailing list