PYTHONWarningSyntax ErrorApril 28, 2026

Syntax Error

SyntaxError: expected ':', got 'def'

What This Error Means

This error occurs when Python expects a colon (:) but instead encounters a different keyword or token, in this case, the 'def' keyword which is used to define a function. This is likely due to a misplaced or incorrect function definition within the code.

Why It Happens

This error typically happens when a programmer attempts to define a function within an existing block of code such as a conditional statement, a loop, or another function, without the proper indentation and syntax.

How to Fix It

  1. 1To fix this error, you should indent the function definition correctly, so that it is at the same level as the outermost block it is intended to be part of, or ensure that you are not attempting to define a function within an existing block of code. For example, if you have a function within a class, ensure that you are using the correct indentation and syntax, like so:
  2. 2// Before (broken code)
  3. 3def foo():
  4. 4 print('Hello')
  5. 5// After (fixed code)
  6. 6def foo():
  7. 7 print('Hello')

Example Code Solution

❌ Before (problematic code)
Python
def foo():
  print('Hello')
  if True:
    print('World')
✅ After (fixed code)
Python
def foo():
    print('Hello')
    if True:
        print('World')

Fix for SyntaxError: expected ':', got 'def'

Related PYTHON Errors

Related PYTHON Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error