Understanding Python Syntax

A guide to Python syntax, including indentation, variables, and comments.

What is Syntax?

In simple terms, syntax is the set of rules that defines the structure of a language. For human languages, it's how words are arranged to form sentences. In the context of programming languages like Python, syntax dictates how we arrange comments, variables, numbers, operators, statements, loops, functions, classes, and objects to convey meaning.

Example of a Comment

A comment in Python is used to explain what a block of code does. It starts with a #, and Python ignores the rest of the line when executing the code.

# This is a comment explaining the following line of code
print("Hello, World!")  # This will print a greeting

Indentation in Python

Indentation is the use of spaces at the beginning of a line to define blocks of code. Unlike many other programming languages where indentation is for readability only, in Python, it is crucial. Python uses indentation to determine the grouping of statements.

Example of Proper Indentation:

for i in range(5):
    print(i)  # This line is indented, part of the for loop

When executed, this code will print the numbers 0 through 4.

Executing Python Syntax

You can execute Python syntax directly in the Command Line or by creating a .py file.

Example in Command Line

>>> print("Hello, World!")
Hello, World!

Example in a Python File

  1. Create a file named myfile.py with the following content:
print("Hello from my file!")
  1. Run it from the Command Line:
C:\Users\Your Name> python myfile.py

Python Indentation

In Python, indentation signifies a block of code. If the indentation is skipped, Python will raise an error.

Example of Proper Indentation:

if 5 > 2:
    print("Five is greater than two!")  # Indented correctly

Example of Missing Indentation:

if 5 > 2:
print("Five is greater than two!")  # This will raise a SyntaxError

Consistency in Indentation

The number of spaces used for indentation is flexible (often 4 spaces is standard), but it must be consistent within the same block of code.

Example:

if 5 > 2:
    print("Five is greater than two!")  # Indentation of 4 spaces
    print("This is still part of the if block.")  # Same indentation

Example of Mixed Indentation Error:

if 5 > 2:
    print("Five is greater than two!")  # 4 spaces
        print("This will raise an error!")  # 8 spaces - SyntaxError