Python Syntax
As discussed earlier, Python code can be executed in two primary ways.
1. Executing Python in the Command Line (Interactive Mode)
Python allows you to run code directly in the command line using its
interactive shell. This is useful for quick testing and learning.
>>> print("Hello, World!")
Hello, World!
Here, the Python interpreter executes the statement immediately and displays
the output.
2. Executing Python Using a .py File (Script Mode)
You can also write Python code in a file with the .py extension and run it
through the command line.
C:\Users\YourName> python myfile.py
This approach is commonly used for building real-world applications and
programs.
Python Indentation
Indentation refers to the spaces at the beginning of a line of code.
Unlike many other programming languages where indentation is only for
readability, indentation is mandatory in Python.
Python uses indentation to define blocks of code such as conditions, loops,
functions, and classes.
Example 1: Correct Indentation (if condition)
Here, the indented line belongs to the if block, so it executes correctly.
Example 2: Missing Indentation (Syntax Error)
❌ This will result in a SyntaxError because the block is not indented.
Spaces in Indentation
You can choose how many spaces to use for indentation, but:
The most common standard is 4 spaces
At least one space is required
Consistency is mandatory within the same block
Example 3: Different Valid Indentations
Both examples work because the indentation is consistent within each block.
Example 4: Inconsistent Indentation (Syntax Error)
❌ Python throws an IndentationError because different indentation levels are
used in the same block.
More Programs to Understand Indentation
Example 5: Indentation with for Loop
Both print statements belong to the loop and will execute three times.
Example 6: Incorrect Loop Indentation
❌ This will cause an error due to missing indentation.