LearningPython TutorialSyntax, Comments & Indentation
CHAPTER 2 · PYTHON BASICS

Python Syntax, Comments & Indentation

Python readable lagta hai because uski syntax clean hai, but whitespace aur indentation ke rules important hote hain. Is chapter me statements, code blocks, colons, comments, line continuation aur common syntax mistakes practical examples ke saath samjhenge.

English + Hinglish42 min readOnline practice included

What is syntax?

Syntax means language ke rules jinke according valid code likha jata hai. Python parser code ko read karke decide karta hai ki structure valid hai ya nahi.

Hinglish Explanation

English sentence me grammar hoti hai; programming language me syntax hoti hai. Agar quotes, brackets, colon ya indentation galat ho, Python code execute karne se pehle hi error de sakta hai.

Python statements

A statement is an instruction that Python executes.

statements.pyPython
course = "Python"
print(course)
print("Keep practicing")

Yahan assignment aur two print() calls separate statements hain.

Try it Yourself →

One statement per line

Beginner code me ek statement per line sabse readable approach hai.

clean.pyPython
name = "Broun"
city = "Lakhimpur"
print(name, city)

Python semicolon se multiple simple statements same line par allow karta hai, but normal application code me readability ke liye generally avoid karo.

avoid.pyPython
name = "Broun"; city = "Lakhimpur"; print(name, city)

Code blocks and indentation

Python braces { } ke instead indentation se blocks define karta hai.

blocks.pyPython
score = 82

if score >= 60:
    print("Passed")
    print("Good work")

print("Result checked")

Indented two lines if block ke andar hain. Last line block ke bahar hai.

Try indentation →

Use 4 spaces per indentation level

Python style convention commonly 4 spaces per indentation level use karti hai.

nested.pyPython
logged_in = True
is_admin = True

if logged_in:
    print("Welcome")
    if is_admin:
        print("Admin tools enabled")
Rule: Same block ki statements ka indentation level consistent hona chahiye.

Tabs and spaces

Editor settings ko spaces par rakhna safest beginner choice hai. Tabs aur spaces ko inconsistent way me mix karne se TabError ya confusing alignment problems aa sakti hain.

Practical setting: Editor me “insert spaces” and indentation width 4 choose karo for Python.

IndentationError

Required block ko indent na karna invalid syntax hai.

broken-indent.pyPython
age = 20

if age >= 18:
print("Adult")

Python expected an indented block after the if line.

Colon starts many compound blocks

if, for, while, def, class, try jaise compound statements me header ke end par colon commonly required hota hai.

colon.pyPython
temperature = 31

if temperature > 30:
    print("Hot day")

Colon bhoolne par SyntaxError mil sakta hai.

Single-line comments

# se comment start hota hai. Python us line ke remaining comment text ko normal executable statement nahi maanta.

comments.pyPython
# Course name shown to the learner
course = "Python"

print(course)  # show current course

Try comments →

Write useful comments

Comments ko obvious code translate karne ke liye nahi, reasoning ya non-obvious intent explain karne ke liye use karo.

comment-quality.pyPython
# Weak: add 1 to attempts
attempts = attempts + 1

# Better: count this failed login toward the retry limit
attempts = attempts + 1

Python has no special multi-line comment token

Multiple comment lines ke liye each line par # use karna clear approach hai.

multi-comment.pyPython
# Load learner settings.
# Keep defaults when optional values are missing.
# Validate before displaying the dashboard.

Triple-quoted strings are not automatically comments

Triple quotes se multi-line string literal banta hai. Function, class or module ke first statement ke रूप me use hone par it can act as a docstring, which is runtime metadata — comment nahi.

docstring.pyPython
def greet():
    """Return a short greeting for the learner."""
    return "Hello"

print(greet())
Remember: Triple-quoted text ko “multi-line comment syntax” bolna technically inaccurate hai.

Blank lines improve readability

Related statements ko group karo and logical sections ke beech blank lines use karo.

readable.pyPython
course = "Python"
chapter = 2

message = f"{course} chapter {chapter}"
print(message)

Long expressions: prefer implicit continuation

Parentheses, brackets aur braces ke andar expressions naturally multiple lines me continue ho sakti hain.

continuation.pyPython
total = (
    120
    + 80
    + 50
)

print(total)

Ye style long expressions ke liye explicit backslash se generally safer/readable hoti hai.

Explicit backslash continuation

Backslash \ se line explicitly continue ki ja sakti hai, but trailing spaces ya edits ise fragile bana sakte hain.

backslash.pyPython
total = 120 + \
        80 + \
        50
Preference: Possible ho to parentheses-based continuation use karo.

Quotes and strings

Single quotes aur double quotes dono string literals ke liye use ho sakte hain.

quotes.pyPython
first = 'Python'
second = "BrounStack"

print(first, second)

Opening quote ko matching closing quote chahiye.

Python is case-sensitive

print and Print same name nahi hain. Keywords and built-ins ko exact case me use karo.

case.pyPython
print("works")
# Print("fails unless you defined Print yourself")

Reserved keywords

Python keywords language grammar ka part hain, so unhe normal variable name ke रूप me use nahi kar sakte.

keywords.pyPython
import keyword
print(keyword.kwlist)

if, for, class, def, return jaise words examples hain. Exact keyword list Python version ke saath evolve ho sakti hai.

SyntaxError vs IndentationError

  • SyntaxError: grammar invalid — e.g. missing colon, unclosed bracket.
  • IndentationError: indentation structure invalid.
  • TabError: tabs/spaces inconsistent in a way Python cannot resolve safely.
Debug habit: Error type, line number, caret marker and message ko carefully read karo.

Readable style and PEP 8

PEP 8 Python code style guide hai. Beginner ke liye key habits: 4-space indentation, sensible blank lines, readable line lengths, spaces around many operators, and clear naming.

spacing.pyPython
# Less readable
result=10+20

# Clearer
result = 10 + 20

Style correctness ka replacement nahi hai, but consistent style code ko easier to read and review banati hai.

Common beginner mistakes

  • Block header ke end me colon bhoolna.
  • Required block ko indent na karna.
  • Same block me inconsistent indentation use karna.
  • Tabs aur spaces mix karna.
  • Print() likhna instead of print().
  • Quotes ya brackets close na karna.
  • Triple-quoted strings ko har context me comments samajhna.
  • One line me unnecessary semicolons use karna.
  • Backslash continuation ko overuse karna.
  • Error line ko read kiye bina random edits karna.

Beginner best practices

  • 4 spaces per indentation level use karo.
  • One statement per line rakho.
  • Comments me intent explain karo.
  • Parentheses-based continuation prefer karo.
  • Logical sections ke beech blank lines use karo.
  • Error messages ko first debugging clue samjho.
  • Code ko Playground me modify karke indentation experiments karo.

Chapter checklist

  • Syntax ka meaning clear hai?
  • Statement aur code block ka basic difference samajh aaya?
  • Indentation Python me structural kyun hai?
  • 4-space convention samajh aayi?
  • # comments likh sakte ho?
  • Triple-quoted string aur comment ka difference clear hai?
  • Colon ka role compound statements me samajh aaya?
  • Implicit line continuation use kar sakte ho?
  • SyntaxError aur IndentationError ko identify kar sakte ho?

Practice Task — Clean Python Syntax

BrounStack Playground me ek small script banao and intentionally syntax experiments karo.

  1. Three separate print() statements likho.
  2. Ek # comment add karo explaining program purpose.
  3. if True: block banao with two indented lines.
  4. Block ke baad one non-indented line add karo.
  5. Colon remove karke error observe karo, then restore karo.
  6. Indentation remove karke IndentationError observe karo.
  7. Nested block ko 4 and 8 spaces ke levels me format karo.
  8. Long arithmetic expression parentheses me multiple lines par likho.
  9. Same expression backslash continuation se test karo.
  10. Ek useful comment aur ek obvious/unnecessary comment compare karo.
  11. Triple-quoted string create karke inspect karo.
  12. keyword.kwlist print karke reserved words dekho.
  13. Semicolon wali one-line version ko readable multi-line version me rewrite karo.
  14. Final script clean format me run karo.