Functions in Python

3

I did this Python exercise, version 2.7:

  

Instructions

     

First, define (def) a function called cube (cube) that   takes an argument called number. Do not forget the   parentheses and colon!

     

Make this function return (return) the cube of that number (that is,   that number multiplied by itself, and then multiplied more   once by itself).

     

Define a second function called by_three that   takes an argument called number.

     

If (if) this number is divisible by 3, by_three should call   cube (number) and return its result. Otherwise, by_three should   return false (return False).

     

Do not forget that if and else statements need one: at the end   from that line!

Here is my code:

def cube(number):
    return number * number * number #number elevado ao cubo(3)

def by_three(number):
    if(number % 3 ==0):
        cube(number)
        print "resultado = %d" % number
    else:
        print "number nao e divisivel por 3"
        return False

But when I run it shows this:

  

Oops, try again. Its function by_three returns None with input 3 when it should return 27. by_three should return cube (n) if n is divisible by 3.

    
asked by anonymous 07.08.2015 / 14:45

1 answer

3

Your problem is on the lines:

    cube(number)
    print "resultado = %d" % number

You call the function cube() passing number , but you forget to do your function by_three() return something, as it does not enter else function code runs to the end without finding any return , and so the return ends up being None .

The return of the cube() function is simply lost. You should return the result of the cube() function, like this:

    return cube(number)

Your code could look like this:

def cube(number):
    return number * number * number  # number elevado ao cubo(3)


def by_three(number):
    if(number % 3 == 0):
        print "resultado = %d" % cube(number)
        return cube(number)
    else:
        print "number nao e divisivel por 3"
        return False

print by_three(3)
    
07.08.2015 / 15:01