Making Code Readable in python programming
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. idi, 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 about how long It would 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 waxinuin 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 a 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 reporter.
No comments:
Post a Comment