Data Science · मराठी आवृत्ती · Python basics
P6.1 Python मध्ये for Loop कसा चालतो?
हे का शिकायचं?
हजार orders चा total हाताने करता येत नाही. Loop प्रत्येक item वर तेच काम करतो.
हे काय आहे?
for item in collection: — प्रत्येक फेरीत item ला पुढची value मिळते आणि indent केलेला code चालतो.
कसं करायचं?
Step 1. for x in list: लिहा.
Step 2. आतला code indent करा.
Step 3. प्रत्येक item वर काम होतं.
Python आणि इतर भाषा: तुलना
या भाषा शिकायची गरज नाही. Python किती सोपा वाचायला आहे ते दाखवण्यासाठी ही table आहे.
| भाषा | Code |
|---|---|
| Python | for b in branches: print(b) |
| Java | for (String b : branches) { System.out.println(b); } |
| JavaScript | for (const b of branches) { console.log(b); } |
| Go | for _, b := range branches { fmt.Println(b) } |
उदाहरणं: copy करा आणि चालवा
उदाहरण A: प्रत्येक item print करा
हा code चालवा:
branches = ["Old Town", "Kazimierz", "Podgorze"]
for b in branches:
print("Branch:", b)
तुम्हाला दिसणारा output:
Branch: Old Town
Branch: Kazimierz
Branch: Podgorze
याचा अर्थ: Loop ने list मधला प्रत्येक item क्रमाने घेतला.
उदाहरण B: Loop ने बेरीज
हा code चालवा:
sales = [1200, 950, 1430]
total = 0
for s in sales:
total = total + s
print(total)
तुम्हाला दिसणारा output:
3580
याचा अर्थ: total = 0 ने सुरुवात करून प्रत्येक फेरीत value जोडली.
उदाहरण C: String वर loop
हा code चालवा:
phone = "+44 20 7946 0958"
digits = 0
for ch in phone:
if ch.isdigit():
digits += 1
print(digits)
तुम्हाला दिसणारा output:
12
याचा अर्थ: String वर loop केला की एक-एक अक्षर मिळतं.