Loop of python repetition

Asked

Viewed 55 times

-1

Hello I have a for that extracts data from an XML file and I wanted to iterate a count to show as for example like this:

1- O EAN é 7897748715180
2- O EAN é None
3- O EAN é 7897748729941
4- O EAN é 7897748729965
5- O EAN é 7897748729880

My code:

import xml.etree.ElementTree as ET
#Bibliotecas
#------------------------------------------------------------------------------------------
XML = input("Coloque o diretorio do XML: ").strip('"')
tree = ET.parse(XML)
root = tree.getroot()
print('\n')

ns = {'nfe': 'http://www.portalfiscal.inf.br/nfe'}
for det in root.findall('.//nfe:det', ns):
    nItem = det.attrib['nItem']
    EAN = det.find('.//nfe:cEAN', ns).text
    
    Contagem = 1
    print(f"{Contagem}- O EAN é {EAN}")
    Contagem = Contagem + 1

I’m doing the Contagem +1 but it’s not adding up, how to add up?

  • 2

    The Count variable setting is inside the for, with each loop set to 1. Move the Count line = 1 to before starting the for, so it will be incremented at each loop

  • It’s true @Pauloc I changed it and it worked

1 answer

4


You are assigning 1 to the value at each step of your loop, that is, the program is adding correctly, but you are "zeroing" the value that was added to each step of the loop.

To solve you can create the variable out of the loop, for this just move the line with the code Contagem = 1 to some line before the for.

Would look like this:

XML = input("Coloque o diretorio do XML: ").strip('"')
tree = ET.parse(XML)
root = tree.getroot()
print('\n')

Contagem = 1
ns = {'nfe': 'http://www.portalfiscal.inf.br/nfe'}
for det in root.findall('.//nfe:det', ns):
    nItem = det.attrib['nItem']
    EAN = det.find('.//nfe:cEAN', ns).text
    
    print(f"{Contagem}- O EAN é {EAN}")
    Contagem = Contagem + 1

You can also use enumerate to create a counter for each iteration of for. Ex:

xml = input("Coloque o diretorio do XML: ").strip('"')
tree = ET.parse(XML)
root = tree.getroot()
ns = {'nfe': 'http://www.portalfiscal.inf.br/nfe'}

for cont, det in enumerate(root.findall('.//nfe:det', ns), start=1):
    ean = det.find('.//nfe:cEAN', ns).text
    print(f"{cont}- O EAN é {EAN}")

  • A lemon made lemonade.

  • I don’t understand Augusto.

  • A question that should be closed managed to create a good answer.

  • ah ok.. hahaha.. I found faster answer than looking for duplicate

Browser other questions tagged

You are not signed in. Login or sign up in order to post.