🟢 Beginner  ·  Lesson 04

Python Syntax, Indentation and Comments

Python Syntax Basics

Syntax means the grammar rules of a language. Python's syntax is famously clean: no semicolons, no curly braces for blocks. Instead, Python uses indentation (spaces at the start of a line) to group code.

Indentation — The Big Rule

In most languages { } mark a block. In Python, the indentation itself defines the block. Lines indented by the same amount belong together.

⚠️ Important

Use 4 spaces per indentation level. Never mix tabs and spaces — it causes an IndentationError.

Comments

Comments are notes for humans; Python ignores them while running.

  • Single-line: start with #
  • Multi-line: wrap text in triple quotes """ ... """

Program 1: Indentation in Action

Python – indent.py
marks = 75

if marks >= 33:
    print("Pass")          # indented = inside the if
    print("Well done!")    # same block
print("Program over")      # not indented = outside the if
Pass Well done! Program over
  • The two indented lines run only when the condition is true.
  • print("Program over") is not indented, so it always runs.

Program 2: Using Comments

Python – comments.py
# This program calculates the area of a rectangle
length = 10      # length in cm
width = 5        # width in cm

area = length * width   # formula: l x w
print("Area =", area, "sq cm")
Area = 50 sq cm

The # notes explain the code without affecting output. Good comments explain why, not just what.

Program 3: Multi-line Strings as Notes

Python – docstring.py
"""
Program: Greeting
Author : Student
Purpose: Print a welcome message
"""
print("Welcome to CodingEasily")
Welcome to CodingEasily

Triple-quoted text at the top is often used to describe a program or function (called a docstring).

Common Mistakes

  • Inconsistent indentation (2 spaces here, 4 there).
  • Mixing tabs and spaces.
  • Forgetting the colon : before an indented block.

Practice Tasks

  1. Write an if-block with two indented lines and one line outside it.
  2. Add a comment above every line of a small program.
  3. Add a 3-line docstring at the top of a program.

Summary

  • Python uses indentation (4 spaces) instead of braces to group code.
  • # makes a single-line comment; """ """ makes a multi-line one.
  • A block always follows a colon :.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.