Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती · Python basics

P6.1 Python मध्ये for Loop कसा चालतो?

By Ravindra Bagale

हे का शिकायचं?

हजार 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 वर काम होतं.

1. Take the next item2. Run the indented block3. More items? Go back to 14. No more items → loop ends
वरून खाली वाचा: code पासून result पर्यंतचा प्रवास

Python आणि इतर भाषा: तुलना

या भाषा शिकायची गरज नाही. Python किती सोपा वाचायला आहे ते दाखवण्यासाठी ही table आहे.

भाषाCode
Pythonfor b in branches: print(b)
Javafor (String b : branches) { System.out.println(b); }
JavaScriptfor (const b of branches) { console.log(b); }
Gofor _, 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 केला की एक-एक अक्षर मिळतं.