The DRY Principle - Don't Repeat Yourself
The DRY or “Don’t Repeat Yourself” principle is a software development practice aimed at reducing repetition of information. In this lesson, you learned how to apply DRY when making comparisons in your Python code.
This code sample from the lesson illustrates how to apply DRY:
name = 'Mahdi'
people_i_like = ['Mahdi', 'John', 'Linda']
if name in people_i_like:
print 'yay!'
00:00 Next, we have a simple example of not repeating yourself.
00:07
Here we want to check to see if Mahdi’s at the party. And we’re only excited if Mahdi, John, or Linda are at the party, and everybody else, we don’t particularly care. So as you can see here, this if
statement has multiple if
statements where we’re checking to see if the name
is equal to one of the names.
00:27
Again, this is fully valid, but you can do this in a better way using Python. You can simply assign the people you like to a list and check to see if the name
is included in that list.
00:40
And 'Mahdi'
is in that list and it prints 'yay!'
. This is a much cleaner way of going about it and allows you to quickly, on the fly, add new names like 'Linda'
is there, 'Lisbon'
, for example, again.
00:55 It’s a pretty cool and pretty easy way of doing things in Python.
Become a Member to join the conversation.