Print element from a specified position in the list

Asked

Viewed 1,432 times

2

I need to get you to print the August days number on the list, but without using the:

def how_many_days(month_number):

    """Returns the number of days in a month.
    WARNING: This function doesn't account for leap years!
    """

days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]

#todo: return the correct value

# This test case should print 31, the number of days in the eighth month, August

print(how_many_days(8))

3 answers

1


Your function is not returning any results, you need to call the Return at the end of the function passing the number of the month -1, the -1 is pq the array starts counting at 0 and not at 1

def how_many_days(month_number):
  """Returns the number of days in a month.
  WARNING: This function doesn't account for leap years!
  """
  days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
  return days_in_month[month_number - 1]

#todo: return the correct value
# This test case should print 31, the number of days in the eighth month, August
print(how_many_days(8))
  • It worked perfectly Jose... thank you.

1

There are two errors in your code:

  1. The return in his role how_many_days
  2. Python needs correct indentation.

For your code to work you need to put the return in function and fix indentation and how python starts in 0 you must return the number of the month - 1, see:

def how_many_days(month_number):
    days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
    return days_in_month[month_number-1];
# This test case should print 31, the number of days in the eighth month, August

print(how_many_days(8))

See working on Ideone.

  • 1

    It worked perfectly... thank you very much.

-1

 def how_many_days(month_number):

   """Returns the number of days in a month.
      WARNING: This function doesn't account for leap years!
   """

   days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]

   return days_in_month[month_number]          
print(how_many_days(7));

That is correct.

  • great... worked really well.

  • Your code is not returning the days of August, but that of September, always good to remember that the array starts counting at 0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.