SwadhyAI Notes

All Python notes

Python Syntax 📝

The Importance of Indentation

In most programming languages (like Java or C++), indentation is just for readability. In Python, indentation is mandatory. It is how Python knows where a block of code starts and ends.

🤖 Analogy: The Outline

Think of Python code like a bulleted list or an outline.
- Main Topic
    - Sub-topic (belongs to Main Topic)
        - Detail (belongs to Sub-topic)
If you mess up the indentation, the structure falls apart!

✨ Correct Syntax

Python uses whitespace (spaces or tabs) to define scope (e.g., loops, functions, if-statements).

python
if 5 > 2:
    print("Five is greater than two!")  # This is indented
    print("This is also inside the if block")

❌ Syntax Error

If you skip the indentation, Python will throw an IndentationError.

python
if 5 > 2:
print("Five is greater than two!") 
# Error: expected an indented block

✨ Pro Tip: Spaces vs Tabs

The official Python Style Guide (PEP 8) recommends using 4 spaces per indentation level.
Most modern code editors (VS Code, PyCharm) automatically convert your "Tab" key press into 4 spaces.

📦 Python Variables

In Python, variables are created the moment you assign a value to them. There is no command for declaring a variable.

python
x = 5           # x is of type int
y = "Hello"     # y is of type str

print(x)
print(y)

⚠️ Watch Out!

You must use the same number of spaces in the same block of code, otherwise Python will give you an error!

python
if 5 > 2:
    print("Five is greater than two!")
        print("Five is greater than two!") # Syntax Error: unexpected indent