What is Python Syntax?
Python syntax is the set of rules that defines how Python code must be written so that the interpreter can understand and execute it correctly. Just like grammar in human languages, these rules govern how statements, expressions, blocks, and other elements are structured in Python.
Python’s syntax is designed to be clear and readable, using English keywords and indentation instead of braces {} to mark blocks of code.
Key Rules of Python Syntax
1. Indentation is Mandatory
In Python, indentation (spaces or tabs at the start of a line) indicates the beginning and end of code blocks, such as under control structures (if, for, while) or function definitions. Incorrect indentation results in a SyntaxError.
Example:
2. Python is Case Sensitive
Variable names, function names, and identifiers distinguish between uppercase and lowercase.
Example: name and Name are two different identifiers.
3. Statements and Line Breaks
Each instruction in Python is a statement and usually appears on its own line. Python does not require semicolons to end statements.
Example:
4. Multiple Statements on One Line
To write more than one statement on the same line, separate them with a semicolon:
This is rarely used in practice but is allowed.
5. Multi-Line Statements
Long expressions can span multiple lines using either a backslash (\) or implicitly within parentheses, brackets, or braces:
Or:
6. Comments
Comments begin with a hash symbol (#) and are ignored by the Python interpreter. They are used to document code or explain logic.
Python does not have a native multi-line comment syntax, but multi-line strings (""" ... """) can serve a similar purpose when not assigned to variables.
Example: A Simple Python Program
This code assigns a string to a variable and prints a greeting. Each element follows Python’s basic syntax rules.