Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

using a dict in time_machine challenge

why isn't this code working? I thought using a dict would make for dryer code, but for some reason the results aren't as expected.

import datetime

starter = datetime.datetime(2015, 10, 21, 16, 29)
time_types = {"minutes": minutes, "seconds":seconds, "hours":hours}
# Remember, you can't set "years" on a timedelta!
# Consider a year to be 365 days.

## Example
# time_machine(5, "minutes") => datetime(2015, 10, 21, 16, 34)
def time_machine(int1, clock1):
  if clock1 == "years":
    delta = datetime.timedelta(days = int1 * 365)
  else:  
    delta = datetime.timedelta(time_types[clock1] = int1)
  ender = starter + delta
  return ender 

1 Answer

Here are the problems:

#first problem
time_types = {"minutes": minutes, "seconds":seconds, "hours":hours}

#second problem
delta = datetime.timedelta(time_types[clock1] = int1)

The value of "minutes" is minutes, python sees this value as an undefined variable. The same for seconds and hours.

The second problem is that you are assigning the variable of the timedelta as a dict's value, I think this way of assignment isn't correct but I cannot explain the reasons because I don't know them, if someone else knows please explain.