🟢 Beginner · Lesson 04
Python Syntax, Indentation और Comments
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 काम में
Python – indent.py
marks = 75
if marks >= 33:
print("Pass") # indented = if के अंदर
print("Well done!") # same block
print("Program over") # बिना indent = if के बाहरPass
Well done!
Program over
- दोनों indented lines तभी चलती हैं जब condition true हो।
print("Program over")indent नहीं है, इसलिए हमेशा चलती है।
Program 2: Comments का Use
Python – comments.py
# यह program rectangle का area निकालता है
length = 10 # length cm में
width = 5 # width cm में
area = length * width # formula: l x w
print("Area =", area, "sq cm")Area = 50 sq cm
# notes code समझाते हैं बिना output बदले। अच्छे comments क्यों बताते हैं, सिर्फ क्या नहीं।
Program 3: Multi-line Strings notes के रूप में
Python – docstring.py
"""
Program: Greeting
Author : Student
Purpose: Print a welcome message
"""
print("Welcome to CodingEasily")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
:के बाद आता है।
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.