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
Beautiful is better than ugly.
Sparse is better than dense.
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.
# Sparse example of sum of squares of numbers in the listdef sum_of_squares_sparse(numbers):total = 0for num in numbers:total += num ** 2return total# Dense implementationdef sum_of_squares_dense(numbers):return sum([x ** 2 for x in numbers])# Test the functionsnumbers = [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
Simple is better than complex.
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:
# This program calculates the sum of the first n natural numbersn = 10sum = 0for i in range(1, n+1):sum += iprint("The sum of the first", n, "natural numbers is:", sum)
This simple and ...
Get hands-on with 1400+ tech skills courses.