Sure, global variables (i.e., names assigned to values outside of any function or class) are convenient. We’ll talk about how to avoid repetition below. If you want to know more, read the excellent summary found on this page. More importantly, repeating the same logic in different places means that eventually one of them will likely be wrong. Yes, we realize that you can just cut and paste and change a few symbols.īut as a programmer, your aim should be to automate repetition, not do it yourself. This violates a fundamental tenet of programming: Don’t repeat yourself (DRY). The other mortal sin in the code snippet above is repetition.īlocks of logic (such as the loop to generate time series) are repeated with only minor changes. To alter the time series length, you only need to change one value Then in the loops, 49 should be replaced by time_series_length - 1. Should certainly be replaced by named constants.įor example, the code above could declare the variable time_series_length = 50. While numeric literals are not all evil, the numbers shown in the program above These kinds of numeric literals in the body of your code are sometimes called “magic numbers”. If you look at the code above, you’ll see numbers like 50 and 49 and 3 scattered through the code. In those settings, coding style matters a great deal.įortunately, lots of smart people have thought about the best way to write code. There are usually many different ways to write a program that accomplishes a given task.įor small programs, like the one above, the way you write code doesn’t matter too much.īut if you are ambitious and want to produce useful things, you’ll write medium to large programs too.
Let’s talk about why that’s the case, and what we can do about it. True, the code more or less follows PEP8.Īt the same time, it’s very poorly structured. legend ( loc = 'upper left', frameon = True ) plt.
plot ( k, 'o-', label = rf "$\alpha = $" ) axes. rcParams = ( 10, 6 ) # Allocate memory for time series k = np.
Import numpy as np import matplotlib.pyplot as plt plt.