Python Syntax
Python syntax is simple, clean, and easy to read.
Unlike many programming languages, Python relies on indentation and readable structure instead of brackets or semicolons.
Python Indentation
Indentation in Python is mandatory.
It defines blocks of code such as loops, conditions, and functions.
If indentation is incorrect, Python raises an error.
Important
Python uses spaces or tabs for indentation, but spaces are recommended.
Code Example 1: Correct Indentation
python
if 10 > 5:
print("10 is greater than 5")
Code Example 2: Indentation in Loop
python
for i in range(3):
print(i)
print("Inside the loop")
Code Example 3: Indentation Error Example
python
if 5 > 2:
print("This will cause an error")
Python Variables
Variables are used to store data values in Python.
Python creates variables automatically when you assign a value.
Python variables:
- Do not need type declaration
- Can change type dynamically
Key Rule
A variable name must start with a letter or underscore.
Code Example 1: Creating Variables
python
name = "Python"
version = 3
Code Example 2: Dynamic Typing
python
x = 10
x = "Ten"
print(x)
Code Example 3: Multiple Assignments
python
a, b, c = 1, 2, 3
print(a, b, c)
Python Comments
Comments are used to explain code and make it more readable.
Python ignores comments during execution.
Python supports:
- Single-line comments
- Multi-line comments (using triple quotes)
Best Practice
Write comments to explain why the code exists, not what it does.
Code Example 1: Single-Line Comment
python
# This is a single-line comment
print("Hello Python")
Code Example 2: Inline Comment
python
x = 10 # This stores a number
print(x)
Code Example 3: Multi-Line Comment
python
"""
This is a multi-line comment.
It is used to describe larger sections of code.
"""
print("Python Comments")