kwekie
kwekie

Reputation: 35

Writing a function that returns the index of an item in a list when the function parameter is the value of a list

had just joined the community and picked up python3 quite recently. Am currently learning through the resource 'How To Think Like A Computer Scientist With Python3, 3rd Edition'. I was working through some exercises on chapter 4: functions and came across this problem: Problem in question

Currently my attempt at the problem is this(please forgive the formatting):

print('-----------Ex 2-----------')

days_of_week = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')


def day_name(n):

    if n >= 0 and n < 7:
        return str(days_of_week[int(n)])
    else:
        return 'None'


print(day_name(1))

print('-----------Ex 3-----------')


def num_day(day_name):

    for day in days_of_week:
        if day == day_name:
            return(days_of_week.index(day_name))
        else:
            return 'None'



print(num_day("Tuesday"))

For exercise 2 everything seems to be working fine, however with exercise 3 the function returns the index of the day together with 'None' as in here:Result

Greatly appreciate any explanation on why this occurs and how to remove the presence of the 'None'

Thanks!

Upvotes: 1

Views: 109

Answers (2)

rich
rich

Reputation: 570

What is happening when you call print(num_day("Tuesday")) is that the for loop iterates through the days of the week. So on the first step of the loop, the variable day is "Monday". Then the if statement is evaluated to false since 'Monday' != 'Tuesday', and so the else block is executed, and the function returns none, which is not what we wanted. Rather we only want to return none after it has iterated through all the week days. So that means we just need to remove the else statement, and return None only if the input did not match any of the week day names.

def num_day(day_name):
    days_of_week = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
    for day in days_of_week:
        if day == day_name:
            return(days_of_week.index(day_name))
    return 'None'

print(num_day("Tuesday"))

Also its better to define the days_of_week variable inside the function.

Upvotes: 0

DerHamm
DerHamm

Reputation: 173

In Python, a function always returns None, if you don't specify any return value. So instead of

print(days_of_week.index(day_name))

You could do

return days_of_week.index(day_name)

So the actual value you want is returned by your function.

Upvotes: 1

Related Questions