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.
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.
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.
course = "Python"
print(course)
print("Keep practicing")Yahan assignment aur two print() calls separate statements hain.
One statement per line
Beginner code me ek statement per line sabse readable approach hai.
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.
name = "Broun"; city = "Lakhimpur"; print(name, city)Code blocks and indentation
Python braces { } ke instead indentation se blocks define karta hai.
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.
Use 4 spaces per indentation level
Python style convention commonly 4 spaces per indentation level use karti hai.
logged_in = True
is_admin = True
if logged_in:
print("Welcome")
if is_admin:
print("Admin tools enabled")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.
IndentationError
Required block ko indent na karna invalid syntax hai.
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.
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.
# Course name shown to the learner
course = "Python"
print(course) # show current courseWrite useful comments
Comments ko obvious code translate karne ke liye nahi, reasoning ya non-obvious intent explain karne ke liye use karo.
# Weak: add 1 to attempts
attempts = attempts + 1
# Better: count this failed login toward the retry limit
attempts = attempts + 1Python has no special multi-line comment token
Multiple comment lines ke liye each line par # use karna clear approach hai.
# 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.
def greet():
"""Return a short greeting for the learner."""
return "Hello"
print(greet())Blank lines improve readability
Related statements ko group karo and logical sections ke beech blank lines use karo.
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.
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.
total = 120 + \
80 + \
50Quotes and strings
Single quotes aur double quotes dono string literals ke liye use ho sakte hain.
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.
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.
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.
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.
# Less readable
result=10+20
# Clearer
result = 10 + 20Style 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 ofprint().- 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.
- Three separate
print()statements likho. - Ek
#comment add karo explaining program purpose. if True:block banao with two indented lines.- Block ke baad one non-indented line add karo.
- Colon remove karke error observe karo, then restore karo.
- Indentation remove karke
IndentationErrorobserve karo. - Nested block ko 4 and 8 spaces ke levels me format karo.
- Long arithmetic expression parentheses me multiple lines par likho.
- Same expression backslash continuation se test karo.
- Ek useful comment aur ek obvious/unnecessary comment compare karo.
- Triple-quoted string create karke inspect karo.
keyword.kwlistprint karke reserved words dekho.- Semicolon wali one-line version ko readable multi-line version me rewrite karo.
- Final script clean format me run karo.