Python For- ja While-silmukat (esimerkkeineen)
⚡ Älykäs yhteenveto
Python Silmukat toistavat koodilohkoa, kunnes tietty ehto täyttyy. For- ja while-silmukat yhdessä break-, continue- ja enumerate-lauseiden kanssa ohjaavat iteraatioiden suorituskertoja, kuten alla olevat esimerkit osoittavat.

Mikä on Loop?
Silmukat voivat suorittaa koodilohkon useita kertoja, kunnes tietty ehto täyttyy. Niiden käyttö on melko yleistä ohjelmoinnissa. Toisin kuin muut ohjelmointikielet, joissa on For Loop, while loop, dowhile jne.
Mikä For Loop on?
For loop is used to iterate over elements of a sequence. It is often used when you have a piece of code which you want to repeat "n" number of time.
Mikä on While Loop?
Vaikka silmukkaa käytetään koodilohkon toistamiseen. Sen sijaan, että koodilohko suoritetaan kerran, se suorittaa koodilohkon useita kertoja, kunnes tietty ehto täyttyy.
Kuinka käyttää "While Loop" -toimintoa
While loop does the exactly same thing what "if statement" does, but instead of running the code block once, they jump back to the point where it began the code and repeats the whole process again.
Syntaksi
while expression Statement
Esimerkki :
# #Example file for working with loops # x=0 #define a while loop while(x <4): print(x) x = x+1
Odotettu tuotos:
0 1 2 3
- Code Rivi 4: Muuttuja x asetetaan arvoon 0
- Code Rivi 7: While-silmukka tarkistaa ehdon x<4. x:n nykyinen arvo on 0. Ehto on tosi. Ohjauskulku siirtyy while-silmukkaan.
- Code Rivi 8: Muodon x arvo tulostetaan
- Code Rivi 9: x:n arvoa kasvatetaan yhdellä. Ohjaus palaa riville 7. Nyt x:n arvo on 1, joka on pienempi kuin 4. Ehto on tosi, ja while-silmukka suoritetaan jälleen. Tämä jatkuu, kunnes x:n arvoksi tulee 4 ja while-ehto muuttuu epätosi.
Kuinka käyttää "For Loopia"
In Python, "for loops" are called iteraattorit.
Just like while loop, "For Loop" is also used to repeat the program.
But unlike while loop which depends on condition true or false. "For Loop" depends on the elements it has to iterate.
Esimerkki :
# #Example file for working with loops # x=0 #define a while loop # while(x <4): # print x # x = x+1 #Define a for loop for x in range(2,7): print(x)
Odotettu tuotos:
2 3 4 5 6
For Loop iteroituu numerolla, joka on ilmoitettu alueella.
Esimerkiksi
Loopille x alueella (2,7)
Kun tämä koodi suoritetaan, se tulostaa numeron väliltä 2 ja 7 (2,3,4,5,6). Tässä koodissa numeroa 7 ei pidetä alueen sisällä.
For Loopsia voidaan käyttää myös muihin asioihin, ei vain numeroihin. Näemme ohuen seuraavassa jaksossa.
For Loop for Stringin käyttäminen
In this step, we will see how "for loops" can also be used for other things besides numbers.
Esimerkki :
#use a for loop over a collection Months = ["Jan","Feb","Mar","April","May","June"] for m in Months: print(m)
Odotettu tuotos:
Jan Feb Mar April May June
Code Line 3: We store the months ("Jan, Feb , Mar,April,May,June") in variable Months
Code Rivi 4: Käymme for-silmukan läpi jokaisen Months-muuttujassa olevan arvon. Months-muuttujassa oleva nykyinen arvo tallennetaan muuttujaan m.
Code Rivi 5: Tulosta kuukausi
Break-lauseiden käyttäminen For Loopissa
Breakpoint on ainutlaatuinen toiminto For Loopissa, jonka avulla voit katkaista tai lopettaa for-silmukan suorituksen
Esimerkki :
#use a for loop over a collection #Months = ["Jan","Feb","Mar","April","May","June"] #for m in Months: #print m # use the break and continue statements for x in range (10,20): if (x == 15): break #if (x % 2 == 0) : continue print(x)
Odotettu tuotos:
10 11 12 13 14
Tässä esimerkissä esitimme luvut 10-20, mutta haluamme for-silmukan päättyvän lukuun 15 ja lopettavan suorituksen. Tätä varten esitimme break-funktion määrittelemällä (x==15): break, joten heti kun koodi kutsuu lukua 15, se lopettaa ohjelman suorittamisen. Code Rivi 10 määrittää muuttujan x väliltä (10, 20)
- Code Rivillä 11 määritellään ehto keskeytyspisteelle kohdassa x==15,
- Code Rivi 12 tarkistaa ja toistaa vaiheet, kunnes se saavuttaa numeron 15
- Code Rivi 13 Tulosta tulos tulosteeseen
"Continue-lauseen" käyttäminen For Loopissa
Jatka-toiminto, kuten nimi osoittaa, lopettaa for-silmukan nykyisen iteraation, MUTTA jatkaa jäljellä olevien iteraatioiden suorittamista.
esimerkki
#use a for loop over a collection #Months = ["Jan","Feb","Mar","April","May","June"] #for m in Months: #print m # use the break and continue statements for x in range (10,20): #if (x == 15): break if (x % 5 == 0) : continue print(x)
Odotettu tuotos:
11 12 13 14 16 17 18 19
Continue-käskyä voidaan käyttää for-silmukassa, kun haluat hakea tietyn arvon luettelosta.
In our example, we have declared value 10-20, but between these numbers we only want those number that are NOT divisible by 5 or in other words which don't give zero when divided by 5.
Joten alueellamme (10,11, 12….19,20) kuuluu vain 3 numeroa (10,15,20), jotka ovat jaollisia viidellä ja loput eivät.
So except number 10,15 & 20 the "for loop" will not continue and print out those number as output.
- Code rivillä 10 määritetään muuttuja x välille (10, 20)
- Code rivi 12 määrittelee ehdon, jossa x jaettuna luvulla 5 = 0, jatka
- Code rivi 13 tulosta tulos
Mikä on enumerate() in Python?
enumerate() PYTHONISSA on sisäänrakennettu funktio, jota käytetään indeksin määrittämiseen iteroitavan objektin jokaiselle alkiolle. Se lisää silmukan iteroitaville objekteille samalla kun se pitääping track nykyisestä alkiosta ja palauttaa objektin numeroituvassa muodossa. Tätä objektia voidaan käyttää for-silmukassa sen muuntamiseen listaksi käyttämällä list()-metodia.
Esimerkki :
Luettelotoiminto käytetään luettelon jäsenten numerointiin tai indeksointiin.
Oletetaan, että haluamme numeroida kuukautemme ( tammi, helmikuu, mars, …. kesäkuu), joten ilmoitamme muuttujan i, joka luettelee luvut, kun taas m tulostaa kuukauden numeron luettelossa.
#use a for loop over a collection Months = ["Jan","Feb","Mar","April","May","June"] for i, m in enumerate (Months): print(i,m) # use the break and continue statements #for x in range (10,20): #if (x == 15): break #if (x % 5 == 0) : continue #print x
Odotettu tuotos:
0 Jan 1 Feb 2 Mar 3 April 4 May 5 June
Kun koodi suoritetaan, enumerate-funktion tulos palauttaa kuukauden nimen indeksinumerolla, kuten (0-tammikuu), (1-helmikuu), (2- maaliskuu) jne.
- Code Rivi 3 ilmoittaa kuukausien luettelon [ tammi, helmikuu,…kesäkuu]
- Code Rivi 4 määrittelee muuttujat i ja m For-silmukkaa varten
- Code Rivi 5 tulostaa tuloksen ja suorittaa jälleen For-silmukan jäljellä olevien kuukausien luettelointia varten.
Käytännön esimerkki
Katsotaanpa toinen esimerkki For Loopilta, joka toistaa saman lausunnon yhä uudelleen ja uudelleen.
| Python silmukka | Työ Code kaikkiin harjoituksiin |
|---|---|
| Code for while-silmukka |
x=0
while (x<4):
print (x)
x= x+1
|
| For Loop yksinkertainen esimerkki |
x=0
for x in range (2,7):
print (x)
|
| For-silmukan käyttö merkkijonossa |
Months = ["Jan","Feb","Mar","April","May","June"]
for m in (Months):
print (m)
|
| Käytä break-lausetta in for loop |
for x in range (10,20):
if (x == 15): break
print (x)
|
| Continue-lauseen käyttö for-silmukassa |
for x in range (10,20):
if (x % 5 == 0): continue
print (x)
|
| Code for "enumerate function" with "for loop" |
Months = ["Jan","Feb","Mar","April","May","June"]
for i, m in enumerate (Months):
print (i,m)
|
Kuinka käyttää for loop -toimintoa saman lauseen toistamiseen yhä uudelleen ja uudelleen
You can use for loop for even repeating the same statement over and again. Here in the example we have printed out word "guru99" three times.
Esimerkki: Toistaaksemme saman lauseen monta kertaa, olemme ilmoittaneet luvun muuttujassa i (i kohdassa 123). Joten kun suoritat koodin alla esitetyllä tavalla, se tulostaa lausunnon (guru99), joka on monta kertaa muuttujalle ilmoitettu luku (i:ssä 123).
for i in '123':
print ("guru99",i,)
Odotettu tuotos:
guru99 1 guru99 2 guru99 3
Kuten muutkin ohjelmointikielet, Python also uses a loop but instead of using a range of different loops it is restricted to only two loops "While loop" and "for loop".
- Vaikka silmukat suoritetaan sen perusteella, onko ehdollinen lause tosi vai epätosi.
- Silmukoita kutsutaan iteraattoreiksi, se iteroi elementin ehtojoukon perusteella
- Python For loops -ohjelmaa voidaan käyttää myös useiden muiden asioiden joukkoon (määrittää elementtien kokoelman, jonka yli haluat silmukan)
- Katkopistettä käytetään For Loopissa ohjelman katkaisemiseen tai lopettamiseen missä tahansa tietyssä kohdassa
- Continue-lause jatkaa lausunnon tulostamista ja tulostaa tuloksen ehtojoukon mukaisesti
- Enumerate function in "for loop" returns the member of the collection that we are looking at with the index number
Python 2-esimerkki
Yllä olevat koodit ovat Python 3 esimerkkiä, jos haluat ajaa sisään Python 2 harkitse seuraavaa koodia.
# How to use "While Loop" #Example file for working with loops # x=0 #define a while loop while(x <4): print x x = x+1 #How to use "For Loop" #Example file for working with loops # x=0 #define a while loop # while(x <4): # print x # x = x+1 #Define a for loop for x in range(2,7): print x #How to use For Loop for String #use a for loop over a collection Months = ["Jan","Feb","Mar","April","May","June"] for m in Months: print m #How to use break statements in For Loop #use a for loop over a collection #Months = ["Jan","Feb","Mar","April","May","June"] #for m in Months: #print m # use the break and continue statements for x in range (10,20): if (x == 15): break #if (x % 2 == 0) : continue print x #How to use "continue statement" in For Loop #use a for loop over a collection #Months = ["Jan","Feb","Mar","April","May","June"] #for m in Months: #print m # use the break and continue statements for x in range (10,20): #if (x == 15): break if (x % 5 == 0) : continue print x #How to use "enumerate" function for "For Loop" #use a for loop over a collection Months = ["Jan","Feb","Mar","April","May","June"] for i, m in enumerate (Months): print i,m # use the break and continue statements #for x in range (10,20): #if (x == 15): break #if (x % 5 == 0) : continue #print x
lähtö:
0 1 2 3 2 3 4 5 6 Jan Feb Mar April May June 10 11 12 13 14 11 12 13 14 16 17 18 19 0 Jan 1 Feb 2 Mar 3 April 4 May 5 June
