python - Elif unexpected indentation when trying to print out single line with total count -
i have created simple function counts number of occurrences in list, however, cannot 1 single line print out total number of occurrences because elif part of if statement creates unexpected indentation error in code. i'm using elif part check whether code entered part of list or not.
so example, instead of getting:
2 entries(s) uk found
i get:
1 entries(s) uk found 2 entries(s) uk found
can please me out suggestion on how correct this? lot !
ps: third week coding, please take easy on me guys.
def mylist(list): countoccurrence = 0 code in list: if code == countrycode: countoccurrence += 1 print str(countoccurrence) + ' entrie(s) ' + str(countrycode) + ' found' elif countrycode not in list: print 'invalid country code' break list = ['ec','us','uk','ur','br','ur', 'ur', 'uk'] countrycode = raw_input('please provide country code > ') mylist(list)
your print
line inside for
loop. consider instead:
def my_func(lst): count = 0 if code not in countrycode: print "invalid country code" return code in lst: if code == countrycode: count += 1 print count
or better:
def my_func(lst): count = lst.count(countrycode) # list.count(x) returns how many times x appears in list if count == 0: print "invalid country code" else: print count
Comments
Post a Comment