मुख्य Python · #3 / 11

Control Flow

if/elif/else, for, while

यह क्यों मायने रखता है

Control flow वह तरीक़ा है जिससे आप समस्या के विवरण को क़दमों में बदलते हैं।

मूल विचार

Conditionals रास्ते चुनते हैं; loops बिना copy-paste के काम दोहराते हैं। जब भी iterable पहले से पता हो, while के बजाय for को प्राथमिकता दीजिए — for को ग़लत पढ़ना मुश्किल है और इसे अनंत बनाना भी मुश्किल है।

आज़माकर देखिए

if / elif / else सीढ़ी, एक छोटे game classifier के साथ:

def grade(score):
  if score >= 90: return "A"
  elif score >= 80: return "B"
  elif score >= 70: return "C"
  elif score >= 60: return "D"
  else: return "F"

for s in [95, 82, 71, 64, 30]:
  print(s, grade(s))
not loaded

for एक range पर, enumerate के साथ ताकि index और value दोनों मिलें:

names = ["Ada", "Linus", "Margaret", "Grace"]
for i, n in enumerate(names, start=1):
  print(f"{i:>2}. {n}")
not loaded

while तब सबसे अच्छा है जब रुकने की शर्त कोई state हो, गिनती नहीं। break जल्दी बाहर निकल जाता है; continue अगली iteration पर छलाँग लगा देता है।

# Find the first square > 100
n = 1
while True:
  if n * n > 100:
      print("first n with n^2 > 100:", n)
      break
  n += 1
not loaded

झटपट जाँच

छोटे अभ्यास

आम ग़लतियाँ

मुख्य बातें