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 trialAdam Niblick
3,157 PointsIs there a better way than if elif?
I am wondering if there is a better way to code this challenge than creating a bunch of "if elif" statements to catch the different possible input strings representing time duration. It seems we should be able to take the string and directly use it as the argument for the datetime.timedelta type.
import datetime
starter = datetime.datetime(2015, 10, 21, 16, 29)
def time_machine(timestr, duration):
if timestr.lower()=='years':
duration=duration*365
td=datetime.timedelta(days=duration)
elif timestr.lower()=='days':
td=datetime.timedelta(days=duration)
elif timestr.lower()=='hours':
td=datetime.timedelta(hours=duration)
elif timestr.lower()=='minutes':
td=datetime.timedelta(minutes=duration)
return starter + td
[MOD: added ```python formatting -cf]
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsThere is nothing wrong with a long chain of elif
statements in Python as there isn't an equivalent to the case
statements of other languages.
If the code provides for catching the "years" condition you can compress the other conditions using dict expansion:
import datetime
starter = datetime.datetime(2015, 10, 21, 16, 29)
def time_machine(duration, timestr):
if timestr.lower()=='years':
duration=duration*365
td=datetime.timedelta(days=duration)
elif timestr.lower() in ['days', 'hours', 'minutes']:
td=datetime.timedelta(**{timestr.lower():duration})
return starter + td
Your original code had the arguments reversed: the duration integer should be first.