Search code examples
pythonfunction

Unable to print the result


I've been going through Codecademy's Python course and I'm currently stuck on 6/19 of the functions chapter. I managed to write the code according to the instructions but I decided to tinker with it a little. This was the initial code I wrote:

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

However, I wanted it to print out the result according to the number I would input in the parentheses below. So this is what I wrote:

def cube(number):
    return number**3
def by_three(number):
    if number % 3 == 0:
        return cube(number)
        print cube(number)
    else:
        return False
        print "False"
cube(5)

I didn't get any errors, but I didn't get the print I wanted either. However, when I put the code in a different Python editor, I got a syntax error on line 6.

What am I missing here?


Solution

  • Your print statements never get executed for two reasons:

    • They follow after the return statements. return exits a function at that point, and any further statements in the function body are ignored as they are never reached.

    • You call the cube() function, not the by_three() function.

    Move your print statements before the return lines, and call he correct function:

    def by_three(number):
        if number % 3 == 0:
            print cube(number)
            return cube(number)
        else:
            print "False"
            return False
    
    by_three(5)
    

    You can replace the print lines with print() function calls to make the code work in a Python 3 interpreter.