Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My if statement keeps returning 'None' for empty list

I'm a beginner at coding in Python and I've been practising with exercises CodeWars.

There's this exercise which basically wants you to recreate the display function of the "likes" on Facebook, i.e. how it shows the number likes you have on a post etc.

Here is my code:

def likes(names):
    for name in names:
        if len(names) == 0:
           return 'no one likes this'
        elif len(names) == 1:
           return '%s likes this' % (name)
        elif len(names) == 2:
           return '%s and %s like this' % (names[0], names[1])
        elif len(names) == 3:
           return '%s, %s and %s like this' % (names[0], names[1], names[2])
        elif len(names) >= 4:
           return '%s, %s and %s others like this' % (names[0], names[1], len(names) - 2)

print likes([])
print likes(['Peter'])
print likes(['Alex', 'Jacob', 'Mark', 'Max'])

This prints out:

None
Peter likes this
Alex, Jacob and 2 others like this

My main issue here is that my first 'if' statement is not producing the string 'no one likes this' for when the argument: [] is empty. Is there a way around this problem?

like image 804
Andy Wang Avatar asked Apr 17 '26 12:04

Andy Wang


2 Answers

If names is an empty list the for loop won't be executed at all, which will cause the function to return None. You should change the structure of your function (hint: you might not even need a loop, not an explicit one at least). There is no point in having a loop and then return on the very first iteration.

like image 134
DeepSpace Avatar answered Apr 20 '26 01:04

DeepSpace


The for loop that you have done occurs one time for each element of the list, but you do non have elements in the list, so the loop won't occour, and the return value will be "None"

def likes(names):
    #for name in names:  #LOOK HERE: you definetly not need this loop
    if len(names) == 0:
       return 'no one likes this'
    elif len(names) == 1:
       return '%s likes this' % (names[0])
    elif len(names) == 2:
       return '%s and %s like this' % (names[0], names[1])
    elif len(names) == 3:
       return '%s, %s and %s like this' % (names[0], names[1], names[2])
    elif len(names) >= 4:
       return '%s, %s and %s others like this' % (names[0], names[1], len(names) - 2)
like image 36
Patrick Roncagliolo Avatar answered Apr 20 '26 01:04

Patrick Roncagliolo