How to fix invalid syntax error on practise makes perfect


#1

this is my code:

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

And this is my error:
File “python”, line 7
else:
^
SyntaxError: invalid syntax

how do i fix this? ive been trying for a few hours yet still nothing works.


#2

My guess is that there’s an indentation problem such that the else: is not aligned at the same level as the if:

def cube(number):
    cube = number ** 3
    return cube

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

print by_three(3)

Indentation matters to Python, as it defines what code belongs to what sections.

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

With the indentation, the if codeblock belongs to the function called by_three(). It only runs when the function runs. The else also belongs to that function.

The return cube(number) belongs to the if. It only runs when the if conditional is True.

The return False belongs to the else:. It only runs if the conditional expression above is False.

Check your indentation.

If it’s correct, then refresh your browser and try it again.


#3

hi and thanks for your reply i did what you said and aligned the else with the if but now theres a new error

this is what the interpreter now says:

File “python”, line 7
else:
^
IndentationError: unindent does not match any outer indentation level


#4

update: sorry i just refreshed and restarted my page and it worked. thank you


#5

This error is telling you that there’s an indentation problem.

Here’s a tip when that happens and you know that the indentation is correct:

  1. Put your cursor at the start of the affected line, e.g. before the else:
  2. Backspace until the else: is inline with the line before it.
  3. Press enter/return on your keyboard to move it to a new line.

The terminal should properly format it for you. This terminal likes 2 whitespaces of indentation.