Some issues of coding about functions


#1



Practice make perfect


These are my code and I don't know what's wrong with it.


def cube(n):
    return cube(n)
def by_three(n):
    if n % 3 == 0:
        return by_three(n)
    else:
        return False


#2

Your first function, cube, is calling itself and it does basically nothing. The second part of the instructions:

  1. Make that function return the cube of that number (i.e. that number multiplied by itself and multiplied by itself once again).

So don't just call to the function, you have to return the cube of your parameter. Use ** to do this.


#3

Thank you for your answer.

However, I tried a new code, and it still shows some errors:

def cube(n):
return n**3
def by_three(n):
if n % 3 == 0:
return by_three(n)
else:
return False


#4

Good job. I cite the instructions again:

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

So why are you calling by_three?


#5

def cube(n):
return n**3
def by_three(n):
if n % 3 == 0:
return n**3
else:
return False

This time it works! But I just guess it....


#6

Let me explain what your current function does:
The first function, cube, returns the cube number of its parameter.
The second function uses the first function to return the cube number of its parameter (again) if it is divisible by 3.

Try to call your function by_three with any number you want. Sprinkling some prints everywhere in the code helps me to understand the code better, maybe you could try it if you didn't catch everything.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.