0

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Blitva
  • 121
  • 1
  • 11
  • 2
    The syntax error is almost certainly caused by you using Python 3. See [Syntax error on print with Python 3](http://stackoverflow.com/q/826948) and [What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?](http://stackoverflow.com/q/25445439) – Martijn Pieters Apr 30 '15 at 20:54

1 Answers1

3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343