The Zen of Python

Check out the twenty principles of the Zen of Python for good programming practices with examples.

Before concluding the course, let’s look at the Pythonic principles of good code with simple examples. These principles are grouped in the Easter egg this.py module. Let’s recap the twenty principles of the Zen of Python with examples.

Make code readable

  1. Beautiful is better than ugly.

  2. Sparse is better than dense.

  3. Readability counts.

Here’s an example. We have a list of numbers. The squares of all numbers are calculated, and then the sum of these squares is calculated. There are two implementations of the same problem: one is sparse, and the other is dense.

Press + to interact
# Sparse example of sum of squares of numbers in the list
def sum_of_squares_sparse(numbers):
total = 0
for num in numbers:
total += num ** 2
return total
# Dense implementation
def sum_of_squares_dense(numbers):
return sum([x ** 2 for x in numbers])
# Test the functions
numbers = [1, 2, 3, 4, 5]
print("Sparse implementation:", sum_of_squares_sparse(numbers))
print("Dense implementation:", sum_of_squares_dense(numbers))

This code is easy to read and understand. It adheres to the following Zen of Python principles:

  • Sparse is better than dense: In the dense implementation, there are too many things going on in the return statement, making it complex and hard to comprehend. On the other hand, the sparse implementation is easy to follow.

  • Readability counts: The code uses easy-to-understand variable and function names and is formatted cleanly.

Keep it simple

  1. Simple is better than complex.

  2. Complex is better than complicated.

Let’s look at an example. Here, we have a simple approach to calculating the sum of the first n integers:

Press + to interact
# This program calculates the sum of the first n natural numbers
n = 10
sum = 0
for i in range(1, n+1):
sum += i
print("The sum of the first", n, "natural numbers is:", sum)

This simple and ...

Get hands-on with 1400+ tech skills courses.