Count


#1

please help me get this code right

def count(sequence,item):
count=0
for x in sequence:
if x==item:
count+=1
else:
return count
print count([1,2,3,3],3)


#3

a function ends the moment a return keyword is reached

so you don't want your function to end the moment x doesn't equal item, you only want to return count after the loop has had a change to count all items in sequence

if a return keyword is reached in a loop, the function still ends immediately the remaining runs/iterations of your loop never happen


#9

yes it did work! so how can i use only (if) statement ,what will the program do if condition is false? why is it not giving me an error?
def count(sequence,item):
count=0
for x in sequence:
if x==item:
count +=1
return count

print count([1,2,3],3)


#10

why not? do something if a specific condition is met

otherwise is just continue with the next iteration of the loop


#11

ok ,yeah that sounds ok ,thanx it helped


#12

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.