Python functions

Asked

Viewed 878 times

3

I did this Python exercise, version 2.7:

Instructions

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

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

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

If (if) this number is divisible by 3, by_three must call Cube(number) and return your result. Otherwise, by_three should return false (Return False).

Don’t forget that if and Else statements need a : at the end of that line!

Here 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 that:

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

  • I think there’s code missing there, no?

  • 1

    I don’t think so...

  • I had read "When executioner, he shows it, "now that I have read it correctly, I realize that I have not understood what your doubt is. I could say which is?

  • The code has a function that calls another function (high number cubed) if it is divisible by 3, it shows the result. but this giving error.

  • I tested in pythonfiddle and it worked its function, did not give any error http://pythonfiddle.com/

1 answer

3


Your problem is on the lines:

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

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

Already the return of the function cube() is simply lost. You should return the function result cube(), thus:

    return cube(number)

Your code could look like this for example:

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)
  • He keeps showing this: Oops, try again. His by_three function returns None with input 3 when it should return 27. by_three should return Cube(n) if n is divisible by 3.

  • Ah, it’s just for a Re-turn instead of a print then

  • I can print something with Return?

  • You can print and return, if it is in your interest

  • OK, thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.