Skip to content Skip to sidebar Skip to footer

Create Function From Try-except

Based on the example provided in this answer, how can I create a function from: from collections import Counter s = ['0', '0', '2', '1', '1', '0', '0', '0'] try: print(next(t[

Solution 1:

You need to return from the except block.

def most_common_number(s):
    try:
        return next(t[0] for t in Counter(s).most_common(2) if t[0] != '0')
    except StopIteration:
        return '0'

Post a Comment for "Create Function From Try-except"