#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. Let's look at 10 ways to make your code more Pythonic. Let's start with these typical big if, elif, elif, elif,
0:14 elif constructs. You must've seen code like this, right? You have the typical workout scheme. We check it Monday, elif Tuesday, Wednesday etc.
0:25 And if it's not a day we raise the ValueError. Now this is pretty ugly but it's also not extensible in the sense that if want another
0:35 maybe combination of Thursday and Friday to do something we have to add another elif. What if we change this in using a dictionary.
0:44 So that we can just look up the key and return a value? I got this picture from the Code Complete Book which is an awesome read about code quality.
0:52 So to refactor that, let's start with defining a workouts dictionary. And I'm just going to copy these in because it's quite some typing. Alright.
1:07 And that gives us a workout scheme. And note that the dates are in random order because it's a dictionary. By the way there's another way
1:15 to make this dictionary. And that is to use zip two sequences. So if I define a list of days and a list of routines, we can do something like workouts
1:29 equals dict of a zip and a zip takes one or more sequences. So days, routines and here you can see we have an equal dict. Alright, now to go back
1:45 to this refactoring example. Now with the dictionary in place you can see how much shorter and nicer this function looks.
1:56 So note I can now just do a get on the dictionary. Looking up the day, and it gives me the routine or None, if today was not found.
2:07 So we can explicitly check routine is None. And raise that ValueError, as we've seen before. And otherwise, just return the routine.
2:27 Let's try it. Chest and biceps. What about Saturday rest
2:46 and call it on nonsense. Yes I get a ValueError because nonsense is not a day. Alright, that's our first refactoring.
2:57 And let's look at counting inside a loop next.