#100DaysOfCode in Python Transcripts
Chapter: Days 34-36: Refactoring / Pythonic code
Lecture: Refactoring 1: if-elif-else horror

Login or purchase this course to watch this video and the rest of the course contents.
0:01 Alright, let's do this.
0:03 Let's look at 10 ways to make your code
0:06 more Pythonic.
0:07 Let's start with these typical
0:09 big if, elif, elif, elif,
0:13 elif constructs.
0:14 You must've seen code like this, right?
0:18 You have the typical workout scheme.
0:20 We check it Monday, elif Tuesday, Wednesday etc.
0:24 And if it's not a day we raise the ValueError.
0:28 Now this is pretty ugly
0:30 but it's also not extensible
0:32 in the sense that if want another
0:34 maybe combination of Thursday and Friday
0:37 to do something we have to add another elif.
0:40 What if we change this in using a dictionary.
0:43 So that we can just look up the key
0:45 and return a value?
0:46 I got this picture from the Code Complete Book
0:49 which is an awesome read about code quality.
0:51 So to refactor that,
0:53 let's start with defining a workouts dictionary.
0:58 And I'm just going to copy these in
1:00 because it's quite some typing.
1:03 Alright.
1:06 And that gives us a workout scheme.
1:09 And note that the dates are in random order
1:12 because it's a dictionary.
1:13 By the way there's another way
1:14 to make this dictionary.
1:16 And that is to use zip two sequences.
1:19 So if I define a list of days
1:21 and a list of routines,
1:23 we can do something like
1:25 workouts
1:28 equals dict of a zip
1:31 and a zip takes one or more sequences.
1:34 So days, routines
1:36 and here you can
1:38 see we have an equal dict.
1:42 Alright, now to go back
1:44 to this refactoring example.
1:46 Now with the dictionary in place
1:48 you can see how much shorter
1:50 and nicer this function looks.
1:55 So note I can now just do a get
1:58 on the dictionary.
2:00 Looking up the day,
2:01 and it gives me the routine
2:03 or None, if today was not found.
2:06 So we can explicitly check routine is None.
2:11 And raise that ValueError,
2:13 as we've seen before.
2:19 And otherwise, just return the routine.
2:26 Let's try it.
2:34 Chest and biceps.
2:37 What about
2:41 Saturday rest
2:45 and call it on nonsense.
2:51 Yes I get a ValueError
2:52 because nonsense is not a day.
2:54 Alright, that's our first refactoring.
2:56 And let's look at counting inside a loop next.