Python Syntax

Before diving deep into Python programming, it's important to understand the basic syntax rules. Python's clean and straightforward syntax makes it an ideal language for beginners. Let's go over how Python code is structured and executed.

Python Syntax Overview

Python code is executed line by line, and indentation plays a key role in defining code blocks (like loops, conditionals, and functions). Unlike many other programming languages, Python does not use curly braces {} or semicolons ;.

Example of a Simple Python Program

print("Hello, Python!")

This is a valid Python program. When run, it prints:

Hello, Python!

Python Indentation

Indentation is not just for readability in Python—it is mandatory. It defines the structure of your code.

Example:

if 5 > 2:
    print("Five is greater than two!")
  • The line under if is indented, which indicates it's part of the if block.
  • Missing or incorrect indentation will result in an error.

Incorrect Example:

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

This will raise an IndentationError.

Python Uses Colons (:)

Colons are used to start a new code block, such as after conditionals, loops, and function definitions.

Example:

if True:
    print("This is true")

Comments in Python

Comments are lines of code ignored by Python during execution. They're useful for explaining code.

Single-line comment:

# This is a comment
print("Hello, world!")  # This is also a comment

Multi-line comments:

Python doesn't have a formal multi-line comment syntax, but you can use triple quotes as a workaround:

"""
This is a multi-line comment
spanning multiple lines.
"""
print("Python ignores the block above")

Python Code Execution

You can write Python code in:

  • The Python Interactive Shell
  • A script file with the .py extension
  • Online interpreters and IDEs like PyCharm, VS Code, or Replit

To run a file from the terminal:

python filename.py

Summary

In this lesson, you’ve learned:

  • Python syntax is clean and easy to read.
  • Indentation is required to define blocks of code.
  • Colons (:) indicate the start of code blocks.
  • Comments help document your code for clarity.