Python syntax
Running Python Code: Two Execution Modes
Python code can be executed in two primary ways: interactive mode (typing code directly into the interpreter) and script mode (writing code in a `.py` file and running it as a program). Understanding both is essential, since each serves a different purpose in real development work.
1. Interactive Mode (Command Line)
Interactive mode lets you type Python statements directly into a shell and see the result immediately after each line. You start it by typing `python` (or `python3` on Linux/macOS) in your terminal without specifying a file.
$ python
Python 3.12.4 (main, Jun 6 2024, 18:45:31)
>>> print("Hello, World!")
Hello, World!
>>> 5 + 3
8The `>>>` symbol is the interactive prompt. It indicates that the interpreter is waiting for input and will execute each statement as soon as you press Enter.
Why it's useful:
- Testing small snippets of code without creating a file
- Quickly checking how a function or expression behaves
- Learning Python concepts step by step
- Debugging by inspecting variable values on the fly
Limitation: Code typed in interactive mode is not saved. Once you close the session, everything is lost — which makes it unsuitable for building actual applications.
Note: To exit interactive mode, type `exit()` and press Enter, or use the shortcut `Ctrl + Z` followed by Enter on Windows, or `Ctrl + D` on Linux/macOS.
2. Script Mode (.py File)
For any real program, Python code is written into a file with a `.py` extension and executed as a whole using the interpreter. This is how virtually all production Python code — web applications, scripts, automation tools — is written and run.
Step 1: Create a file named `myfile.py`:
print("Hello, World!")Step 2: Run it from the command line:
python myfile.pyOn Linux or macOS, use `python3` instead:
python3 myfile.pyOutput:
Hello, World!
Unlike interactive mode, script mode executes every line in the file from top to bottom in a single run and does not display intermediate results unless you explicitly print them.
Interactive Mode vs. Script Mode
| Aspect | Interactive Mode | Script Mode |
|---|---|---|
| Input method | Typed line-by-line in the shell | Written in a `.py` file |
| Execution | Immediate, line by line | Entire file runs at once |
| Output | Auto-displays expression results | Only shows what's explicitly printed |
| Persistence | Not saved after closing | Saved and reusable |
| Best for | Testing, learning, debugging | Real applications and scripts |
Python Indentation
Indentation refers to the whitespace at the beginning of a line of code. In most programming languages (like Java or C++), indentation is optional and used purely for readability, with curly braces `{}` defining code blocks instead. Python is different: indentation is not optional — it is part of the language's syntax.
Why Python Uses Indentation
Python uses indentation instead of braces to define blocks of code, such as the body of an `if` statement, a loop, a function, or a class. This design choice was intentional: it forces consistently readable code, since the visual structure of the code always matches its logical structure.
if 5 > 2:
print("Five is greater than two!")Here, the indented line is part of the `if` block. The interpreter uses this indentation to know that `print(...)` should only execute when the condition `5 > 2` is `True`.What Happens Without Indentation
If a block of code that requires indentation is left unindented, Python raises a `SyntaxError` because it cannot determine where the block begins.
if 5 > 2:
print("Five is greater than two!")File "example.py", line 2
print("Five is greater than two!")
^
IndentationError: expected an indented block after 'if' statement on line 1The interpreter expects an indented statement immediately after the colon (`:`) that follows `if 5 > 2`. Since none is found, it fails before the program even runs.How Many Spaces to Use
Python does not enforce a fixed number of spaces, but it does enforce consistency:
- You can technically use as few as one space.
- The official style guide (PEP 8) recommends 4 spaces per indentation level — this is the convention used across almost all professional Python code.
- All lines within the same block must use the same indentation.
if 10 > 5:
print("Ten is greater than five") # 4 spaces — standard
if 10 > 5:
print("Ten is greater than five") # 8 spaces — still valid
Both examples run without error because each block is internally consistent, even though they use a different number of spaces. However, mixing styles within the *same* block breaks the program:
if 10 > 5:
print("Ten is greater than five")
print("This will cause an error")IndentationError: unexpected indentThe second `print()` uses a deeper indentation level than the first line in the same block, so Python cannot determine whether it belongs to the `if` block or a new, nested block that was never opened.
Warning: Never mix tabs and spaces in the same file. Python 3 explicitly disallows this and raises a `TabError`, because a tab can render as a different number of columns depending on the editor, making the indentation level ambiguous.
Indentation in Loops
The same indentation rules apply to loops. Every statement that should repeat on each iteration must be indented at the same level, directly under the loop declaration.
for i in range(3):
print("Hello")
print("Python")Output:
Hello
Python
Hello
Python
Hello
PythonBoth `print()` statements are part of the loop body because they share the same indentation level. If indentation is removed, Python cannot identify a loop body at all:
for i in range(3):
print("Hello")IndentationError: expected an indented block after 'for' statement on line 1Indentation in Functions
Function bodies follow the exact same rule: every line that belongs to the function must be indented consistently under the `def` line.
def greet():
print("Welcome to Python")
print("Learning is easy")
greet()Output:
Welcome to Python
Learning is easy
Both `print()` statements are part of `greet()`'s body. The call `greet()` on the last line is not indented, which tells Python it belongs to the top-level program, not the function definition — this is what actually triggers the function to run.
Common Mistakes with Python Syntax
1. Missing the colon before an indented block
if 5 > 2
print("Five is greater than two!")Why it's wrong: Python requires a colon (`:`) at the end of any statement that introduces a new block (`if`, `for`, `while`, `def`, `class`, etc.). Without it, Python raises a `SyntaxError`.
if 5 > 2:
print("Five is greater than two!")2. Mixing tabs and spaces
Why it's wrong: Even if the code looks correctly aligned in your editor, Python may interpret tabs and spaces differently, leading to a `TabError: inconsistent use of tabs and spaces in indentation`.
Correct approach: Configure your editor to insert spaces when you press Tab (most modern editors, including VS Code, do this by default with Python files).
3. Inconsistent indentation depth within the same block
As shown earlier, using 4 spaces on one line and 8 spaces on the next line within the same block raises an `IndentationError`. Every statement at the same logical level must use identical indentation.
4. Assuming interactive mode behavior applies to scripts
Beginners sometimes expect an expression like `5 + 3` to automatically display output inside a `.py` file, since that happens in interactive mode. In script mode, you must explicitly use `print()` to see any output.
Best Practices for Python Syntax
- * Follow PEP 8 and use 4 spaces per indentation level — this is the de facto standard across the Python community and expected in any professional codebase.
- Never mix tabs and spaces. Configure your editor to convert tabs to spaces automatically.
- Use a code editor with Python support (VS Code, PyCharm) rather than a plain text editor, since these tools highlight indentation errors before you even run the code.
- Keep indentation consistent across your entire project, not just within a single file — mixed conventions across files make collaboration harder.
- Use interactive mode for experimentation, but always move finished logic into `.py` files for anything meant to be reused or shared.
- Avoid deeply nested blocks (more than 3–4 levels of indentation) where possible — it usually signals that a function is doing too much and could be broken into smaller functions.