Making Code Readable

Much like there are spaces in English sentences to make the words easier to read, we use spaces in Python code to make it easier to read. In particular, we always put a space before and after every binary operator. For example, we write v = 4 + -2.5 / 3.6 instead of v=4+-2.5/3.6. There are situations where it may not make a difference, but that’s a detail we don’t want to fuss about, so we always do it: it’s almost never harder to read if there are spaces.

Psychologists have discovered that people can keep track of only a handful of things at any one time (Forty Studies That Changed Psychology [Hoc04]). Since programs can get quite complicated, it’s important that you choose names for your variables that will help you remember what they’re for. id1, X2, and blah won’t remind you of anything when you come back to look at your program next week: use names like celsius, average, and final_result instead.

Other studies have shown that your brain automatically notices differences between things—in fact, there’s no way to stop it from doing this. As a result, the more inconsistencies there are in a piece of text, the longer it takes to read. (JuSt thInK a bout how long It w o u l d tAKE you to rEa d this cHaPTer iF IT wAs fORmaTTeD like thIs.) It’s therefore also important to use consistent names for variables. If you call something maximum in one place, don’t call it max_val in another; if you use the name max_val, don’t also use the name maxVal, and so on.

These rules are so important that many programming teams require members to follow a style guide for whatever language they’re using, just as newspapers and book publishers specify how to capitalize headings and whether to use a comma before the last item in a list. If you search the Internet for programming style guide (https://www.google.com/search?q=programming+style+guide), you’ll discover links to hundreds of examples. In this book, we follow the style guide for Python from http://www.python.org/dev/peps/pep-0008/.

You will also discover that lots of people have wasted many hours arguing over what the “best” style for code is. Some of your classmates (and your instructors) may have strong opinions about this as well. If they do, ask them what data they have to back up their beliefs. Strong opinions need strong evidence to be taken seriously.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.242.235