0

Edited to reword question.

The problem in the attached code is that as soon as we enter the for loop the variables: gcOne, gcTwo, gcThree are out of scope, so I cannot use them inside the for loop (in the print statement 2 there is nothing to print).

How to pass or use the local variables gcOne, gcTwo, gcThree in the for loop?

Thanks.

#!/usr/local/bin/python3.10
# Ensure this script will run using Python 3.10

# Include some libraries
import xml.etree.ElementTree

xml_tree = xml.etree.ElementTree.parse("sampledata.xml")
root = xml_tree.getroot()

gcOne="1"
gcTwo="2"
gcThree="3"


# Read the XML file
def process_xml(element, gcOne, gcTwo, gcThree):
        element_tag = element.tag
        element_attributes = element.attrib if len(element.attrib) else ""
        element_text = element.text if element.text is not None and len(element.text.strip()) > 0 else ""
        element_tail = element.tail.strip() if element.tail is not None and len(element.tail.strip()) > 0 else ""

        if element_tag == "gcA":
                gcOne=element_text

        if element_tag == "gcB":
                gcTwo=element_text

        if element_tag == "gcC":
                gcThree=element_text
                # Now do something with gcOne, gcTwo and gcThree because we have values for all 3 variables (note: assumes this order in the xml file for simplicity)

        # This line is printing the value of one of gcOne or gcTwo or gcThree
        print ("1 ", gcOne, gcTwo, gcThree)

        # Read further elements recursively
        element_children = list(element)
        for child in element_children:
                # This is not printing any of gcOne, gcTwo, gcThree but always prints 1, 2, 3
                print ("2 ", gcOne, gcTwo, gcThree)
                process_xml(child, gcOne, gcTwo, gcThree)

        return gcOne, gcTwo, gcThree


# Main
process_xml(root, gcOne, gcTwo, gcThree)
Adi
  • 91
  • 1
  • 3
  • Your global variables of the same name have nothing to do with the local variables in your function. note, since it's recursive, each call gets it own set of local variables. Also, you are doing nothing with the return values, simply discarding them – juanpa.arrivillaga Feb 24 '22 at 16:32
  • In any case, your for loop would not magically assign `None` to those variables,(which is what I *assume* you meant by empty/null) so you really must provide a [mcve]. – juanpa.arrivillaga Feb 24 '22 at 16:34

0 Answers0