Home/Blog/Programming/The Zen of Python
Home/Blog/Programming/The Zen of Python

The Zen of Python

11 min read
May 02, 2023

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

The Zen of Python is a set of golden principles or axioms for the best programming practices in Pythonic style. These guiding principles were first presented by Tim Peters, one of Python's founding contributors, in 1999. They first appear in a mailing list of Python programmers (comp.lang.python/python-list@python.org), to comp.lang.python/python-list@python.org under a thread called “The Way of Python”under a thread called "The Way of Python", in the form of a lyric. These so-called principles became very popular among the community of Python developers and had an influence on the development process. In fact these were eventually incorporated into the official Python Enhancement Proposal (PEP20) in 2004. Today, the Zen of Python is considered a fundamental philosophy of the language and serves as a cornerstone of best practices for Python programming.

Much of these guidelines are attributed toward the benevolent dictator of life (BDFL) BDFL is a title given to a small number of open-source software development leaders who retain the final say in disputes or arguments in the community of Python, Guido van Rossum. According to Tim Peters, these principles were his design philosophy while developing the language.

Note: Benevolent dictator for life (BDFL) is a title given to a small number of open-source software development leaders who retain the final say in disputes or arguments in the community. Guido voluntarily stepped down from the title of Python’s BDFL in 2018.

While programming, these guidelines don't have to be strictly followed. However, these are good programming practices that define the Pythonic way of programming.

These best practices are added into Python language in this.py module as a string object.

widget

How to import this#

These best practices guidelines can be viewed by simply importing the this.py program.

Barry WarsawOpen-course contributor-cum-musician-cum-ThaiChi master, one of the leading Pythonista, creator of Jython, and GNU Mailman added The Zen of Python into the Python language as an Easter egg a hidden piece of functionality, in the software, executed through a set of undocumented commands back in 2001. These 19 guiding principles can be imported using import this in the Python IDE.

import this

Note:  A video of Barry Warsaw singing The Zen of Python, which he composed himself, can be found on YouTube.

The 20 golden aphorisms of Zen#

These principles can be grouped into categories. So the order might be a bit different than what is seen in this.py.

Make code readable#

  1. Beautiful is better than ugly.

Focus on simplicity, readability, and elegance. Often, developers are not concerned about the readability while coding. However, Python emphasizes well-thought-out and easy-to-use code. That's what makes Python so popular.

  1. Sparse is better than dense.

Writing one-liner codes that incorporates a lot of functionality may seem alluring to programmers, however, it becomes cumbersome to read. Instead of compressing the code into one line or the minimum number of lines, it's better to keep the code sparse, spanning over multiple lines, for better readability.

  1. Readability counts.

The code should be easy to read. Using appropriate, easy-to-understand names for variables and functions helps. The use of sufficient comments in the code helps any developer who wants to understand and use the code in the future. Making good use of line spacing and indentation helps improve readability.

Example:

Here's a simple example where we have list of numbers. The squares of all numbers are calculated, and then sum of these squared are 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 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])

This code is easy to read and understand. It follows The Zen of Python principles, such as:

  • 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.

If there's a complex problem, break it down into several simpler modules and solve it. For a simple problem, obviously, keep it simple, and don't go looking around for a complex approach.

  1. Complex is better than complicated.

If things can't be made simpler, don't make things complicated. Never make things, solutions, or the code complicated.

Example:

Here's an example of a simple approach to calculating the sum of the first n integers:

# 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 easy-to-understand code follows several of The Zen of Python principles such as:

  • Keep it simple: The algorithm to calculate the sum of the first n integer is straightforward.

  • Readability counts: The code uses variable names and clean formatting, making it easy to read and understand.

Follow best practices#

  1. Flat is better than nested.

Too much nesting and hierarchy make the code hard to read and understand. The code should be organized as flatly as possible.

  1. Special cases aren't special enough to break the rules.

It's best to follow the standard best practices to develop the algorithm and write the code instead of trying to create a new approach.

  1. Although practicality beats purity.

Well, there is no alternative to experience. If the code is readable and easy to follow, some of the principles may be deviated to serve the purpose of practicality.

  1. Namespaces are one honking great idea -- let's do more of those!

Use namespaces to avoid conflicts while naming the variables. Different namespaces may coexist, but these are isolated from each other. Names in one module do not conflict with the names in another.

Example:

Here's an example of how to follow best practices in Python, making maintainable and robust code:

# This program reads a CSV file and prints out the data
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(', '.join(row))

The code follows several best practices of Python programming, for example:

  • Use of a context manager to handle file I/O: The with statement is used to close the file after reading is complete. It ensures that resources are released properly after the file has been read.

  • Use of a library to handle CSV parsing: The csv module is used to read and parse the CSV data. It ensures that the data is read correctly.

  • Use of clear and descriptive variable names: The descriptive variable names make the code easy to understand and readable.

Handle Errors#

  1. Explicit is better than implicit.

No prior knowledge should be required for someone who wants to read a program, so keep it as explicit as possible.

  1. Errors should never pass silently.

If there is a silent error, the code returning None or some other error code, should not let it pass silently. That might create some bugs in the future and would be hard to trace back. Instead of a program running with a silent error, it's better if it crashes, and gets fixed it in time.

Remember: As the saying goes, "Seeing a spider in the room isn't scary. It's scary when it disappears."

  1. Unless explicitly silenced.

Some errors or warnings are unavoidable, so make these silent by using the commands to ignore the errors or warnings. However, it should be known where and why these errors or warnings are made silent.

  1. In the face of ambiguity, refuse the temptation to guess.

Always debug instead of making some wild guesses. If the output is not lining up with the solution, instead of making some blind attempts, It's better to understand the problem critically and reach for the right solution.

Example:

Let's look at the following example of calculating the inverse of an integer. Error handling ensures smooth execution of the program.

# This program calculates the inverse of a number
try:
num = float(input("Enter a number: "))
inverse = 1.0 / num
print("The inverse of", num, "is:", inverse)
except ValueError:
print("Error: Input must be a number")
except ZeroDivisionError:
print("Error: Cannot divide by zero")

To handle the errors gracefully, the program does the following:

  • Uses a try-except block to catch errors: The code calculates the inverse of a number within a try block. It catches possible errors with except blocks.

  • Handles specific errors: There could be two specific errors that are handled in two separate except blocks— ValueError for invalid input and ZeroDivisionError for division by zero.

  • Prints informative error messages: The code prints informative error messages, making it easy for the user to understand and correct the error.

Concise#

  1. There should be one-- and preferably only one --obvious way to do it.

If there are multiple possible solutions, go for the simplest and most obvious solution, and try not to complicate things.

  1. Although that way may not be obvious at first unless you're Dutch Guido van Rossumis Dutch.

The obvious way may not be that obvious at the first sight. However, an expert (none other than the DutchmanGuido van Rossum himself) may read things between the lines because he knows Python inside out.

Example:

The following example prints the first 10 even numbers in a concise way:

# This program prints the first 10 even numbers
even_numbers = [num for num in range(20) if num % 2 == 0]
print(even_numbers[:10])

This program follows several of The Zen of Python principles such as:

  • Simple is better than complex: The code doesn't introduce any unnecessary complexity, keeping it concise and easy to understand.

  • Readability counts: The code uses appropriate variable names and clean formatting, making it readable and easy to understand.

  • There should be one-- and preferably only one --obvious way to do it: The code uses list comprehension, which is a Pythonic way to generate lists based on a condition. This is a common way of solving this problem in Python.

Clean code#

  1. Now is better than never.

Follow 'the power of now'. A program should not get into an infinite execution.

  1. Although never is often better than right now.

At times, it is better to wait rather than to quickly jump to the consequences. It's better to wait for the program execution rather than to terminate it early.

Example:

Here's an example that calculates Fibonacci numbers. Notice the code is kept clean and maintainable.

# This program calculates the Fibonacci sequence
def fibonacci(n):
"""Return the Fibonacci sequence up to n."""
a, b = 0, 1
fib_sequence = []
while b <= n:
fib_sequence.append(b)
a, b = b, a + b
return fib_sequence
# Example usage
result = fibonacci(100)
print(result)

The programming logic ensures the code does not end up in an infinite loop. This example follows several principles of clean code, including:

  • Use of clear and descriptive names: The function is named fibonacci, which accurately describes what it does. The variables a, b, and fib_sequence make the code easy to understand.

  • Use of docstrings to document functions: The function has a docstring that explains what it does.

  • Modular approach: The calculation of the Fibonacci sequence is encapsulated in a function, making it modular and easier to maintain.

  • Clear and concise code: Simple logic calculates the Fibonacci sequence — no complexity, no redundancy.

Easy to explain#

  1. If the implementation is hard to explain, it's a bad idea.

Can it be explained to Joe at the coffee shop? If a developer reads the code in the future, they should easily understand it. If someone can't understand it, that means some of the principles above were not followed.

  1. If the implementation is easy to explain, it may be a good idea.

If other developers can easily get the work, the work is on the right track. The solution may not be optimal or correct, but at least it follows simplicity and readability principles.

Example:

Here's an example that counts the frequency of each word in a file. The code is easy to explain with clear and concise logic:

# This program counts the number of occurrences of each word in a file
from collections import Counter
with open("text.txt", "r") as file:
word_count = Counter(file.read().split())
for word, count in word_count.items():
print(f"{word}: {count}")

This code is easy to explain because it uses simple logic to count the number of occurrences of each word in a file. It follows several of The Zen of Python principles to keep the code concise and explainable, such as:

  • Use of the Counter class from the collections module: This class provides a simple and efficient way to count the number of occurrences of each item in an iterable.

  • Use of a with statement to handle file I/O: This ensures that the file is properly closed after reading. This helps keep the code concise and readable.

  • Use of descriptive variable names: The variable word_count accurately describes its function. So does the loop variable word.

  • Print an informative message: The code uses an f-string to print out each word and its count in a clear, readable format.

The 20th principle#

Initially, there were 20 principles planned. Wondering where the 20th principle is? It has been left for Guido to fill in, which unfortunately has not been done so far by Guido van Rossum.

widget

Key takeaways#

The Zen of Python emphasizes the importance of readability, simplicity, clarity, consistency, and good coding practices. When learning to code in Python, you should know how to develop a program that is easy to understand, modify, and maintain.

In short, the guiding principles of The Zen of Python can be summarized as follows:

  • Write code that is easy to read and understand, keeping simplicity, clarity, and explicitness as the main focus.

  • Handle errors gracefully and provide informative error messages.

  • Follow established best practices and conventions, and strive for consistency and clarity in your code.

widget

The following courses on Educative platform help developers learn and test their Pythonic way of coding:


Written By:
Aamir Shahzad Hashmi
 
Join 2.5 million developers at
Explore the catalog

Free Resources