Python Syntax, Indentation और Comments
Written and reviewed by Gagan Bhardwaj · Senior IT Faculty · 15+ years’ experience
Python Syntax की मूल बातें
Syntax यानी language के grammar नियम। Python की syntax मशहूर रूप से साफ है: न semicolons, न blocks के लिए curly braces। इसके बजाय Python code को group करने के लिए indentation (line की शुरुआत में spaces) use करता है।
Indentation — सबसे बड़ा नियम
ज़्यादातर languages में { } block बनाते हैं। Python में indentation खुद block तय करता है। समान मात्रा में indent की गई lines एक साथ होती हैं।
हर indentation level के लिए 4 spaces use करें। tabs और spaces कभी न मिलाएं — IndentationError आता है।
Comments
Comments इंसानों के लिए notes हैं; Python चलाते समय इन्हें ignore करता है।
- Single-line:
#से शुरू - Multi-line: text को triple quotes
""" ... """में लपेटें
Program 1: Indentation काम में
marks = 75
if marks >= 33:
print("Pass") # indented = if के अंदर
print("Well done!") # same block
print("Program over") # बिना indent = if के बाहर- दोनों indented lines तभी चलती हैं जब condition true हो।
print("Program over")indent नहीं है, इसलिए हमेशा चलती है।
Program 2: Comments का Use
# यह program rectangle का area निकालता है
length = 10 # length cm में
width = 5 # width cm में
area = length * width # formula: l x w
print("Area =", area, "sq cm")# notes code समझाते हैं बिना output बदले। अच्छे comments क्यों बताते हैं, सिर्फ क्या नहीं।
Program 3: Multi-line Strings notes के रूप में
"""
Program: Greeting
Author : Student
Purpose: Print a welcome message
"""
print("Welcome to CodingEasily")ऊपर triple-quoted text अक्सर program या function describe करने के लिए use होता है (इसे docstring कहते हैं)।
सामान्य गलतियाँ
- असंगत indentation (कहीं 2 spaces, कहीं 4)।
- tabs और spaces मिलाना।
- indented block से पहले colon
:भूलना।
Practice Tasks
- दो indented lines और एक बाहर वाली line के साथ if-block लिखें।
- छोटे program की हर line के ऊपर comment जोड़ें।
- Program के ऊपर 3-line docstring जोड़ें।
सारांश
- Python braces की जगह indentation (4 spaces) से code group करता है।
#single-line comment;""" """multi-line।- Block हमेशा colon
:के बाद आता है।