Typically, aesthetic programming was not a critical issue when we were studying in school. Individuals then follow their style when writing in Python. However, the work may be quite undesirable whenever we have to spend most of the time understanding one’s implicit code, which could also happen to others when reading our code. Therefore, let’s focus on the Zen of Python and some improvement tips to solve the problem.
For those who haven’t seen it before, type and execute import this
in your Python interpreter, and 19 guiding principles penned by Tim Peters will show up:
In this piece, I’m going to share my interpretation of these aphorisms and some useful Python tips I’ve learned.
Photo by June Wong on Unsplash.
Python features simple syntax, code readability, and English-like commands that make coding a lot easier and more efficient than with other programming languages. For example, using or
and
vs. ||
&&
to construct the same expressions in semantic perspective**:**
# &&, ||
if a == 0 && b == 1 || c == Ture:
# and, or
if a == 0 and b == 1 or c == Ture:
# These are the same logical expression in Python
# The alternative operators can be used to construct the exact same expressions from a semantic perspective.
alternative_operator.py
Furthermore, the layout and composition of the code are crucial, and there are plenty of resources that exist covering this topic. Here is the most popular and my favorite one:
https://www.python.org/dev/peps/pep-0008/
After looking through PEP8, take a look at these articles showing some highlights and applications:
Never mess up your code. Be elegant and make it beautiful.
In Python, a good naming convention not only prevents you from getting bad grades in classes but also makes your code explicit. Fortunately, there are some guidelines you can find in PEP8, and I would like to highlight some points below.
my_list
.list_of_machine_learning_data_set
.Everything has to be lucid and understandable.
“Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.” ― Steve Jobs
A lot of times when dealing with iterators, we also need to keep a count of iterations. Python eases the task by providing a built-in function called enumerate()
. Here is the immature way followed by the recommended one:
words = ['Hannibal', 'Hanny', 'Steeve']
# Novice
index = 0
for word in words:
print(index, word)
index += 1
# Pro
for index, word in enumerate(words):
print(index, word)
Another example is using the built-in zip()
function, which creates an iterator that would pair elements from two or more iterables. You can use it to solve common programming problems fast and efficiently, like creating dictionaries.
subjects = ['math', 'chemistry', 'biology', 'pyhsics']
grades = ['100', '83', '90', '92']
grades_dict = dict(zip(subjects, grades))
print(grades_dict)
zip_app.py
The ability to simplify is to eliminate the unnecessary so that the necessary may speak.
The difference between complex and complicated is that complex is used to refer to the system level of components, while complicated refers to a high level of difficulty.
Sometimes, although we try to keep tasks simple and stupid, the result could still be nasty. In this case, optimization in programming becomes necessary, and my favorite option of learning it is working on coding challenge websites. You can view others’ solutions and even be inspired by better algorithms.
HackerRank provides a variety of levels fitting new programmers, which is outstanding for getting started. After that, try websites that are more professional, like:
https://www.coderbyte.com/challenges
https://www.topcoder.com/challenges/?pageIndex=1
Nested modules are not common in Python—at least I haven’t seen anything like module.class.subclass.function
before—and not easy to read. Though building a submodule in another submodule may reduce lines of code, we don’t want users to get troubled with unintuitive syntax.
Don’t stress the reader by sticking too much code in one line. A recommended maximum line length is 79 characters. The limitation of the editor window width works well when using code review tools.
Download images agiler from Unsplash using Python.
Code is read more often than it’s written. Think about indentation and how much easier it is to read code, and compare the codes below:
money = 10000000
print("I earn", money, "dollars by writing on medium.")
money = 10_000_000
print(f"I earn {money} dollars by writing on medium.")
In this case, the codes share the same result, but the last one provides more readability by using underscore placeholders and f-string. After Python 3.6 was announced, f-string started to make formatting easier and it’s more powerful when dealing with longer sentences with more variables inside.
A writer’s style should not place obstacles between his ideas and the minds of his readers.
The consistency of supporting general cases is the key, so try to reorganize a cumbersome project into a simple form. For example, structure the code in classes or sort it into different files according to its functionality, even though Python doesn’t force you to do so. Since Python is a multi-paradigm programming language, a powerful approach to problem-solving is to create objects, which is known as object-oriented programming.
Object-oriented programming is a programming paradigm that organizes program structure so that attributes and behaviors can be viewed as individual objects. The benefit of it is intuitive and easy to manipulate, and many tutorials have splendidly explained the concepts. This one is my favorite:
This aphorism is contradictory to the last one and reminds us of the balance between them.
Passing errors would eventually leave implicit bugs that are even harder to figure out. Thanks to the robust error handling in Python, it is not difficult for programmers to use the tool compared with other languages.
try:
x = int(input("Please enter an Integer: "))
except ValueError:
print("Oops! This is not an Integer.")
except Exception as err:
print(err)
else:
print('You did it! Great job!')
finally:
print('ヽ(✿゚▽゚)ノ')
# 1.The code that potentially break down.
# 2.Triggered if the value error occur.
# 3.Handling error other than value error.
# 4.Execute if no error triggered.
# 5.Execute no matter the error triggered or not.
exception_handling.py
According to Python’s documentation: “Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.”
Especially for a big project, we don’t want our code crashing after a time-consuming computation. This is why exception management is charming.
In some situations, small bugs would not bother you. Maybe you want to catch the specific error, though. To get more details on specific error messages, I recommend reading the official Built-in Exceptions document and finding out your target.
https://docs.python.org/3/library/exceptions.html
“What is important is to keep learning, to enjoy challenge, and to tolerate ambiguity. In the end there are no certain answers.” ― Matina Horner
This quote is elegant and lyrical but not a good metaphor in programming. Ambiguity may refer to unclear syntax, complicated program structure, or mistakes that trigger an error message. For example, a simple mistake when using the numpy
module for the first time:
import numpy as np
a = np.arange(5)
print(a < 3)
if a < 3:
print('smaller than 3')
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
If you execute the code above, you’ll find an array of five bools in the output indicating the values under 3. Thus it’s impossible for the if
statement to determine the state. The built-in .all()
and .any()
functions showed in the message are used for successive And/Or.
import numpy as np
a = np.array([True, True, True])
b = np.array([False, True, True])
c = np.array([False, False, False])
print(a.all())
print(a.any())
print(b.all())
print(b.any())
print(c.all())
print(c.any())
all_any_demo.py
The output shows that .all()
returns True
only if all of the items are True
, while .any()
returns True
if any of the items are True
.
Think of why Python is described as an easy-to-learn programming language. With marvelous built-in functions/libraries and high expansibility, Python encourages programmers to write gracefully. Though there are more solutions to provide flexibility, it could spend too much time digging into the same problem.
The creator of Python, Guido van Rossum, is a Dutch programmer who makes this aphorism unarguable. You won’t claim that you know Python better than he does… at least I won’t.
Photo courtesy of Guido van Rossum on GitHub.
“You may delay, but time will not, and lost time is never found again.” — Benjamin Franklin
For those who suffer from procrastination like me and are searching for change, check this out and cooperate with the panic monster.
On the other hand, another side of the aphorism is to stop you from over-planning, which is no more productive than watching Netflix.
The mutual attribute of procrastination and over-planning is that
“Nothing is done.”
“Now is better than never” doesn’t mean that planning is useless. Writing the ideas down and setting a goal to conquer is better than doing it at the very moment. For example, I usually spend an hour every Sunday to scratch out my weekly schedule and update my plan for tomorrow right before I go to bed to check out anything that has to be put off.
Recall the idea of “Complex is better than complicated.” Usually, the complicated code means weak design—especially in high-level programming languages like Python. In some cases, however, the complexity of its domain knowledge could make implementation hard to explain, and how to optimize its lucidity matters. Here’s a guideline for structuring projects that leverages your achievement.
https://docs.python-guide.org/writing/structure/
It’s programming expertise to make the design (or even people’s lives) easier while the background knowledge may be profound, and I think this is the hardest part of programming.
Take advantage of the simplicity and readability in Python to implement crazy ideas.
Last but not least, a namespace is a set of symbols that are used to organize objects of various kinds so that these objects may be referred to by unique names. In Python, a namespace is a system composed of:
print()
function.
Diagram of namespace relations.
The namespace system prevents Python from conflicting between module names.
Thanks for reading! I hope you enjoyed it.
☞ Python Tutorials for Beginners - Learn Python Online
☞ Learn Python in 12 Hours | Python Tutorial For Beginners
☞ Complete Python Tutorial for Beginners (2019)
☞ Python Programming Tutorial | Full Python Course for Beginners 2019