The following section shows the Python statement syntax by comparing Python statements with statements from other programming language.
Consider the following if statement, coded in a C-like language:
if (x > y) {
x = 1;
y = 2;
}
This might be a statement in C, C++, Java, JavaScript, or similar.
Now, look at the equivalent statement in the Python language:
if x > y:
x = 1
y = 2
The one new syntax component in Python is the colon character :
All Python compound statements, which have other statements nested inside them, uses a header line terminated in a colon, followed by a nested block of code.
The nested block of code are indented underneath the header line, like this:
Header line: Nested statement block
The colon is required.
Parentheses are optional
The set of parentheses around the tests at the top of the statement:
if (x < y)
The parentheses are not required by Python.
if x < y
The parentheses are not treated as an error if present.
You won't need the semicolon in Python code to end your line.
x = 1;
You can leave off the semicolons, and it works the same way:
x = 1
You don't need to include begin/end, then/endif, or braces around the nested block, as you do in C-like languages:
if (x > y) {
x = 1;
y = 2;
}
In Python, we consistently indent all the statements in a given single nested block the same distance to the right.
Python uses the statements' physical indentation to determine where the block starts and stops:
if x > y:
x = 1
y = 2
Indentation is the blank whitespace all the way to the left of the two nested statements.
Python doesn't care how you indent (spaces or tabs), or how much you indent (use any number of spaces or tabs).
The indentation of one nested block can be totally different from that of another.
For a given single nested block, all of its statements must be indented the same distance to the right.