0

my code only loops once then return only one data. below is my code

def test():

for element_regFile in root.findall('country'):
    csvdataElement=[]

    filename=element_regFile.find('name')
    if filename != None:
        filename=filename.text
    else:
        filename='None'
    csvdataElement.append(filename)

    return csvdataElement

Then, i want to print the output of the function one by one as shown below:

print test()
>>>> [London]
>>>> [Paris]

The print statement will be outside the function

Below is my xml:

    ?xml version="1.0"?>
<data>
    <country >
        <name>London</name>
        <rank>1</rank>
        <abc>123</abc>
        <year>2008</year>
        <gdppc>141100</gdppc>
    </country>
        <country >
        <name>Paris</name>
        <rank>1</rank>
        <year>2010</year>
        <gdppc>68000</gdppc>
    </country>
</data>

It should return London and Paris. But unfortunately, it only return London.

2 Answers2

0

This is indentation problem. print statement should have same indentation like for :

for element_regFile in root.findall('country'):
    csvdataElement=[]

    filename=element_regFile.find('name')
    if filename != None:
        filename=filename.text
    else:
        filename='None'
    csvdataElement.append(filename)

print(csvdataElement)
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
0
for element_regFile in root.findall('country'):
    csvdataElement=[]
    filename=element_regFile.find('name')
    if filename != None:
        filename=filename.text
    else:
        filename='None'
    csvdataElement.append(filename)
    print(csvdataElement)
mohammed wazeem
  • 1,310
  • 1
  • 10
  • 26
  • it shows both name; London and Paris. But the data is in one list; [London,Paris]. I would like to make it in a difference list ; [London] [Paris] –  Apr 03 '20 at 05:59
  • @vause You mean nested list. something like this `[["London"], ["Paris"]]` – mohammed wazeem Apr 03 '20 at 06:08
  • No, in a difference list. First, it will return [London] , the it will return [Paris]. Sorry , im new this Python thingy. –  Apr 03 '20 at 06:12
  • Can you provide the output you want from your test `function`? – mohammed wazeem Apr 03 '20 at 06:16
  • I already provide the output in my question above. –  Apr 03 '20 at 06:34
  • @vause Anyway I have updated the above answer. But there is nothing to do with appending item into the list and printing it, Because there should be only one item at each iteration. – mohammed wazeem Apr 03 '20 at 06:39
  • I see, it is impossible to use return statement? Thanks a lot –  Apr 03 '20 at 06:43
  • @vause Yup A return statement ends the execution of the function call and "returns" the result. You can use but this is not the case you wanted. – mohammed wazeem Apr 03 '20 at 06:44