For loop


#1



Exercise:
Write a function, tag_count, that takes as its argument a list of strings. It should return a count of how many of those strings are XML tags. XML is a data language similar to HTML. You can tell if a string is an XML tag if it begins with a left angle bracket "<" and end with a right angle bracket ">".
You can assume that the list of string that will be given as input will not contain empty strings.


My code print only 1, I dont know why... I found this exercice online, looking for something to help me with another Codecademy exercise and now...I'm really stuck with this one, And..I think it's very simple but I can't figured out.
Thanks for help!


def tag_count(list1):
	suma = 0
	for item in list1: 
		if item[0] == "<" and item[-1] == ">": 
			suma += 1
			return suma 
		

# Test for the tag_count function:
list1 = ['<greeting>', 'Hello World!', '</Hi>']
count = tag_count(list1)
print("Expected result: 2, Actual result: {}".format(count))


FIXED: 

def tag_count(list1):
	suma = 0
	for item in list1: 
		if item[0] == "<" and item[-1] == ">": 
			suma += 1
	return suma


#2

a function ends the moment a return keyword is reached, so you want to have a loop to check if each item might be an xml/html tag, then after the loop return suma (you forgot the a at the end of suma as well)

else: False doesn't really do anything, remove it


#3

thank you for yur help.
(false removed).


#4

if a return keyword is reached in a loop, the function needs to end, so the loop breaks

so, your function, once a match is found, your function ends. The rest of the list is not checked for more hits

place return outside the loop so the whole loop can run result in a correct total and not a maximum of one


#5

thank so much,,,,

its working now :slight_smile:

def tag_count(list1):
suma = 0
for item in list1:
if item[0] == "<" and item[-1] == ">":
suma += 1
return suma


#6

here is how i would have solved it:

def tag_count(list1):
	return sum(1 for item in list1 if item[0] == "<" and item[-1] == ">")
list1 = ['<greeting>', 'Hello World!', '</Hi>']
count = tag_count(list1)
print("Expected result: 2, Actual result: {}".format(count))

using a generator expression.

good you made it work and understand where you went wrong :slight_smile:


#7