The Zen of Python With Examples
Python’s architecture and philosophy are encapsulated in a series of aphorisms called The Zen of Python. You can access it by entering “import this” in a Python interpreter or code editor. It was created by Tim Peters. The Zen of Python tenets are listed below, along with examples that clarify what they mean:
The Zen of Python
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
Beautiful is better than ugly.
Example:
Ugly code:
def f(x): return 2*x**2-3*x+1
Beautiful code:
def quadratic_function(x): return 2*x**2 - 3*x + 1
Explicit is better than implicit.
Example:
Implicit:
def add(a, b): return a + b
Explicit:
def add(a: int, b: int) -> int: return a + b
Simple is better than complex.
Example:
Complex code:
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1)
Simple code:
def factorial(n): result = 1 for i in range(1, n + 1): result *= i return result
Complex is better than complicated.
Example:
Complicated code:
def process_data(data): # Complicated data processing logic here... return result
Complex but organized code:
def process_data(data): # Complex data processing, but structured and well-documented... return result
Flat is better than nested.
Example:
Nested code:
def nested_function(a): if a > 0: if a % 2 == 0: return "Positive even number" else: return "Positive odd number" else: return "Non-positive number"
Flat code:
def flat_function(a): if a > 0 and a % 2 == 0: return "Positive even number" elif a > 0: return "Positive odd number" else: return "Non-positive number"
Sparse is better than dense.
Example:
Dense code:
data = [x for x in range(10) if x % 2 == 0]
Sparse code:
data = [] for x in range(10): if x % 2 == 0: data.append(x)
Readability counts.
Example:
Less readable code:
x=5;y=10;result=x+y;print(result);
More readable code:
x = 5 y = 10 result = x + y print(result)
Special cases aren’t special enough to break the rules.
Example:
Non-compliant:
def divide(a, b): if b == 0: return "Cannot divide by zero!" else: return a / b
Compliant:
def divide(a, b): return a / b
Although practicality beats purity.
Example:
Pure code:
def calculate(a, b): result = a * b + a - b return result
Practical code:
def calculate(a, b): return a # A more practical implementation
Errors should never pass silently.
Example:
Silently passing errors:
def divide(a, b): return a / b
Explicit error handling:
def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero!") return a / b
Unless explicitly silenced.
Example:
Silenced error:
try: result = divide(10, 0) except ValueError as e: print(e)
Explicitly handling the error:
try: result = divide(10, 0) except ValueError as e: print("An error occurred:", e)
In the face of ambiguity, refuse the temptation to guess.
Example:
Ambiguous code:
x = "10" y = 5 result = x + y # Raises TypeError: can only concatenate str (not "int") to str
Explicit conversion to avoid ambiguity:
x = "10" y = 5 result = int(x) + y
There should be one—and preferably only one—obvious way to do it.
Example:
Multiple ways to calculate the factorial:
import math def factorial(n): return math.factorial(n) def factorial_alternative(n): result = 1 for i in range(1, n + 1): result *= i return result
One obvious way:
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1)
Although that way may not be obvious at first unless you’re Dutch.
Example:
Obfuscated code (not recommended):
def f(x): return 2*x**2-3*x+1
More readable version:
def quadratic_function(x): return 2 * x ** 2 - 3 * x + 1
Now is better than never.
Example:
Delayed implementation:
def future_feature(): # To be implemented in the future... pass
Implementing it now:
def current_feature(): # Implementation of the current feature pass
Although never is often better than right now.
Example:
Hasty code (not thoroughly tested):
def calculate(a, b): # Quickly written code... return a / b
Taking the time to write and test code properly:
def calculate(a, b): if b == 0: raise ValueError("Cannot divide by zero!") return a / b
If the implementation is hard to explain, it’s a bad idea.
Example:
Confusing code:
def complex_algorithm(x, y): # Complex algorithm with unclear purpose return result
Clearly-explained code:
def calculate_area(length, width): return length * width
If the implementation is easy to explain, it may be a good idea.
Example:
Simple and clear implementation:
def greet(name): return f"Hello, {name}!"
Overly complex implementation:
def greet(name): # Complex logic to greet the user return result
Namespaces are one honking great idea—let’s do more of those!
Example:
Proper use of namespaces:
import math def calculate_area(radius): return math.pi * radius ** 2
Avoiding global namespace pollution:
def calculate_area(radius): pi = 3.14159 return pi * radius ** 2
Remember, the Zen of Python emphasizes the importance of writing clean, readable, and straightforward code that adheres to Python’s philosophy, making it easier for others to understand and collaborate on projects.
Also Read:
Python Fundamentals Guide for Beginners