Python Syntax और Indentation
In this page:
if condition:
# indented block
statement
else:
statement
Line Statements
Python statements semicolon के बजाय newline character पर खत्म होते हैं, इसलिए print("hi") वाली line line खत्म होते ही पूरी हो जाती है — अंत में कोई punctuation ज़रूरी नहीं।
आप semicolon से दो statements को एक line में ठूँस भी सकते हैं, लेकिन यह शायद ही कभी Python की शैली माना जाता है।
उदाहरण: Line Statements
print("hi") # statement ends at the newline, no semicolon required
print("no semicolon needed")
print("a"); print("b") # semicolon lets two statements share one line
Indentation के नियम
जहाँ C-परिवार की भाषाएँ statements को समूह में बाँधने के लिए { } इस्तेमाल करती हैं, वहीं Python इसके बजाय एकसमान indentation का उपयोग करती है — interpreter whitespace को केवल सजावट नहीं, बल्कि संरचनात्मक syntax मानकर parse करता है।
इसे गलत करना सिर्फ़ गंदा नहीं दिखता, बल्कि यह बदल देता है कि कौन सा code किस if, loop या function का हिस्सा है।
उदाहरण: Indentation Rules
if True: # condition is always true
print("Indented block belongs to the if") # indented line is inside the if block
print("Back to outer level") # not indented, so it runs regardless of the if
Block की संरचना
एक ही indentation स्तर के सभी statements को एक block माना जाता है, जो उसे खोलने वाले if, loop या function से संबंधित होता है; block तब खत्म होता है जब कोई line कम indent पर लौट आती है।
जिसे एक block होना चाहिए, उसके भीतर अलग-अलग indentation गहराई मिलाने पर code चुपचाप गलत समूह में जाने के बजाय IndentationError उठता है।
उदाहरण: Block Structure
if True:
print("first line of block") # first statement in the if block
print("second line, same indent") # same indent level, still part of the block
print("outside the block") # dedented, so it's outside the if block
Multi-line Statements
किसी line के अंत में backslash \ Python को बताता है कि statement अगली line में जारी है, जो लंबी expression को तोड़कर पढ़ने योग्य रखने के काम आता है ताकि वह उचित line लंबाई से आगे न जाए।
जो expressions पहले से parentheses, brackets या braces के अंदर हैं, वे बिना backslash के भी कई lines में लिखी जा सकती हैं।
उदाहरण: Multi-line Statements
total = 1 + 2 + \
3 + 4 # backslash continues the statement onto this line
print(total)
total2 = (1 + 2 +
3 + 4) # parentheses allow wrapping without a backslash
print(total2)
Syntax Errors
indentation की दो सबसे आम गलतियाँ हैं tabs और spaces को मिलाना (जो editor में एक जैसे दिख सकते हैं पर interpreter के लिए अलग हैं) और colon के बाद नए block को indent करना भूल जाना।
अपने editor को Tab key पर spaces डालने के लिए configure करने से पहली समस्या पूरी तरह टल जाती है।
उदाहरण: Syntax Errors
# Common mistakes:
# 1. Mixing tabs and spaces in the same block
# 2. Forgetting to indent after a colon
if True:
print("correctly indented")
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: