Kuba loop kwiPython

I-loop kwiPython ineempawu ezahlukileyo kunezinye iilwimi zokucwangcisa. Ndinishiya into endiyifundayo ukuze ndifumane okuninzi kwezona ziluphu zisetyenziswa kakhulu.

KwiPython yenzelwe ukuphinda-phinda into enokuphinda iphindwe, nokuba luluhlu, into, okanye enye into.

Ulwakhiwo olulandelayo lu

h2=[ 'Valencia', 'Castellón', 'Alicante']

for j in h2:
   instructions

Apha i-h2 yinto enokuphinda ilandelelwe umzekelo uluhlu h2=[ 'Valencia', 'Castellón', 'Alicante']. Iluphu iya kuba nophindaphindo olu-3, kweyokuqala j=Valencia kweyesibini utshintsho j=Castellón.

Kwaye ngale nto sinokuyichaza imiyalelo esiyifunayo, sihlala sikhumbula i-indentation, into ebalulekileyo kwiPython kwaye abantu abaninzi abayihoyi, befumana iimpazamo kwikhowudi.

Phinda iluphu inani elichanekileyo lamaxesha.

Ukuba sifuna iphinda inani elithile lamaxesha njengoko sinokwenza kwi-C++ kuya kufuneka sisebenzise uluhlu (). Ukuphindaphinda amaxesha ali-10 siza kusebenzisa u-a

for element in Range(9):
    instructions

Sibeka u-9 kwaye hayi u-10 kuba Uluhlu luqala ku-0, ngoko ke ukusuka ku-0 ukuya ku-9 kukho uphindaphindo lwe-10 okanye ujiko lwelophu.

Ukwazi Uluhlu () kusivumela, endaweni yokubeka inani ngaphakathi, ukubeka uguquko, esiya kuba nolawulo oluninzi.

var = 10
for element in Range(var):
    instructions

Umsebenzi weRange unokhetho oluninzi, ndiya kuthetha ngako kwelinye iposi, ukuze ungaxubi umxholo kwaye uphuhlise kangangoko kunokwenzeka.

Kuninzi okunokwenziwa ukulawula ukuhamba kwelophu.

Qhoboza kwaye Qhubeka neeNgxelo

Kukho izinto ezi-2 eziluncedo kakhulu ezisivumela ukuba senze i-loop esebenza kakhulu, ikhefu kunye nokuqhubeka. Ngokuqhelekileyo zisetyenziswa kunye neemeko, ukuba, ukujonga ukuba kukho into eyinyani.

Basebenza kwezinye iilophu, kwaye kukho enye inkcazo enomdla edlulayo, eyingxelo eyenziwayo kodwa engenzi nto kwaye ifanelekile xa sifuna ukuchaza isakhiwo esifuna imiyalelo kodwa sifuna ukuyibeka kamva (izimvo zilungile). ayiloncedo kulento)

ikhefu

Ngekhefu sinokuphuma kwi-loop nangaliphi na ixesha. Njengoko ucinga luncedo kakhulu. Kuyinyani ukuba kukho ezinye izakhiwo ezinje nge-Ang,

numeros = [1, 2, 4, 3, 5, 8, 6]
for n in numeros:
    if n == 3:
        break
else:
    print('No se encontró el número 3')

Qhubeka

Isenza ukuba siye kwinto elandelayo kwiluphu.

numeros = [1, 2, 4, 3, 5, 8, 6]
for n in numeros:
    if n == 3:
        continue
else:
    print('No se encontró el número 3')

https://j2logo.com/bucle-for-en-python/

Kuba ... okunye

Kukho ulwakhiwo oluthatyathwe kwi-For, eye ... okunye

datos = [1, 2, 3, 4, 5]
for n in datos:
    if n == 2:
        break
else:
    print('No hay 2')

Esi sakhiwo savela emva kokubona ukuba kuyimfuneko kwaye abantu abaninzi basebenzisa ezinye iindlela zokuphumeza oku. Ngaloo ndlela, banceda abantu kwaye bafumane ikhowudi efundeka ngakumbi

kuba _ ngokuphindaphindiweyo

Ndiyibonile le nto kwezinye iinkqubo nangona ndingazange ndiyisebenzise.

Xa siphinda-phinda into, uluhlu, isichazi-magama, njalo njalo, kodwa umxholo wezo zinto awufuni kuthi, singawubonisa ngo- _

Umzekelo:

Sifuna ukubala izakhi zoluhlu kodwa asikhathali nokuba luqulathe ntoni na, sifuna nje ubude balo.

h2=[ 'Valencia', 'Castellón', 'Alicante']
count = 0
for _ in h2:
    cont += 1

Kwiindawo ezininzi bacebisa ukuba bangasebenzisi kakubi lo mkhuba. Andazi ngenene i-advantages eyibonisayo, ingaba iyakhawuleza?

ukujikela ngasemva

ngasemva kwilophu. Ukuphindaphinda ukusuka ekugqibeleni ukuya ekuqaleni

Isebenzisa umva () umsebenzi ongeniswe kwipython 3

h2=[ 'Valencia', 'Castellón', 'Alicante']

for j in reversed(h2):
    print (j)

I-Loping ene-indices ezimbini, ixabiso le-iterable kunye nesalathisi

Nge enumerate() singasebenza kunye nezalathi zengqokelela. Ngenxa yokuba amaxesha amaninzi, ukongeza kwixabiso lezinto ezinokuphinda ziphindeke, sinomdla kwisalathiso sayo.

h2=[ 'Valencia', 'Castellón', 'Alicante']

for j, h in enumerate(h2):
    print j, '-->', h2[i] 

Uphindaphinda izintlu ezi-2

Olunye ukhetho olunomdla kakhulu yi-zip () eya kwenza umsebenzi wethu ube lula kwaye izakwenza ikhowudi yethu ibe lula kwaye ifundeke ngakumbi.

h2=[ 'Valencia', 'Castellón', 'Alicante']
cod=[100, 200, 300]

for j, h in zip(h2, cod):
    print h2, '-->', cod 

KwiPython 2.x izip() yasetyenziswa ukwenza lo msebenzi, kodwa kwiPython 3 izip yizip()

Ukuvula ngolungelelwano olucwangcisiweyo

Phinda ngokulandelelana ngexabiso lento endaweni yesalathiso sayo. i- sorted() iyasetyenziswa

colors = ['rojo', 'amarillo', 'verde']

for color in sorted(colors):
    print color

Kwaye ukuba sifuna ukuyenza ngasemva

colors = ['rojo', 'amarillo', 'verde']

for color in sorted(colors, reverse=True):
    print color

Ukuhlela ngokwesiko

colors = ['rojo', 'amarillo', 'verde']

for color in sorted(colors, key=len):
    print color

Ixabiso leSentinel kwilophu

Ixabiso lomlindi lixabiso elibangela ukuba iluphu iphele. Ihlala iboniswa kwi-loop yexeshana, kodwa uRaymond Hettinger usibonisa indlela yokuyisebenzisa nge-, ekhawulezayo.

blocks = []
for block in iter(partial(f.read, 32), ''):
    blocks.append(block)
    print (block)

Tyhila izichazi-magama nge for

Izichazi-magama zizixhobo ezibalulekileyo zokuvakalisa ubudlelwane nokwenza amaqela.

Ungadlula kwisichazimagama ngendlela yemveli nge, kodwa loo nto ayizukubuyisela lonke ulwazi, asizukwazi ukusebenza ngamaxabiso kunye nezalathisi ezinje, ukuba asiqalisi ukongeza izinto zokubala kunye nezinye izinto.

d = {'casa': 'azul', 'coche': 'rojo', 'hombre': 'verde'}

for k in d.keys():
    if k.startswith('r'):
        del d[k]

Ngale ndlela, ukongeza ekuboneni izakhi, singakwazi ukulungisa isichazi-magama ngokutshintsha iziqalelo okanye ukuzicima, kwangaxeshanye i-loop iphindwaphindwa.

d.keys() ibiza iingxoxo kwaye yenza ukhuphelo elugcina kuluhlu esinokuluguqula.

Ukufumana izalathisi kunye namaxabiso endaweni yento yemveli kwaye yinto yokuqala ethi qatha engqondweni yethu kwabo baqala inkqubo

for k in d:
    print k, '-->', d[k]

Siza kusebenzisa olu khetho lukhawuleza kakhulu

for k, v in d.items():
    print k, '-->', v

izinto() kunezinto()

Thetha malunga neeLoops kwiPython nguRaymond Hettinger

Yividiyo endala kodwa ebonisa kakhulu, apho kwimizuzu engama-20 yokuqala uRaymond Hettinger esifundisa ngamathuba ahlukeneyo e-loops ePython kwaye usinika imizekelo yendlela abaguqula ngayo izakhiwo ezisetyenziswa ngokubanzi ngabantu zibe yimisebenzi, ukwenza i-loop ifundeke ngakumbi kwaye ibe lula. ikhowudi.

Shiya amazwana