Python for Introductory StatisticsXYZ Homework Edition

⇩ Download ▾

3.3 Syntax Errors

Watch demo video

Incorrectly written command or instruction will cause a failure in execution. For example, indentation (any length) and : (colon) are part of the syntax for the if statement. In the program below, colon : is missing in the first line.

Example: In the code below, colon is missing in the first line of the if condition.

if 2 < 3                       # colon : is missing
  print("It is less than!")
elif 2 > 3:
  print("It is greater!")
else:
  print("Equal!")
Show error output
  File "<ipython-input-102-e5ff2ebb180c>", line 1
    if 2 < 3                       # colon : is missing
                                                       ^
SyntaxError: invalid syntax

Example: In the code below, indentation is missing in the block statement of the if condition in line 2.

if 2 < 3:
print("It is less than!")   # block statement needs indentation
elif 2 > 3:
  print("It is greater!")
else:
  print("Equal!")
Show error output
  File "<ipython-input-103-3c294b21dd46>", line 2
    print("It is less than!")   # block statement needs indentation
        ^
IndentationError: expected an indented block

Example: When an undeclared variable is used in a statement, it causes error messages. In the code below, slope was not defined ahead of the if condition.

if slope > 0:                # slope is not defined can not be compared to zero
  print('increasing')
else:
  print('decreasing')
Show error output
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-105-942dc7b20bf4> in <module>()
----> 1 if slope > 0:                # slope is not defined can not be compared to zero
      2   print('increasing')
      3 else:
      4   print('decreasing')

NameError: name 'slope' is not defined

Adapted from Python for Introductory Statistics, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.