Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The Zen of Python

The Zen of Python

Presented at the PyLadies Bangalore November meetup, this presentation explains the Zen of Python in brief

Bhoomika Agarwal

November 24, 2018
Tweet

More Decks by Bhoomika Agarwal

Other Decks in Programming

Transcript

  1. Summary 1. History 2. The Zen of Python 3. Meaning

    of some of the aphorisms in The Zen of Python 4. Resources 5. Questions @myriadbhoom
  2. PEP20--TheZenofPython Author: Tim Peters [email protected] Created : 19-Aug-2004 Post history:

    22-Aug-2004 Long time Pythoneer Tim Peters succinctly channels the BDFL’s guiding principles for Python’s design into 20 aphorisms, only 19 of which have been written down. @myriadbhoom
  3. TheZenofPython-1 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. @myriadbhoom
  4. TheZenofPython-2 There should be one -- and preferably only one

    -- obvious way to do it. 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. Although that way may not be obvious at first unless you’re Dutch. Namespaces are one honking great idea -- let’s do more of those. Now is better than never. Although never is often better than *right* now. @myriadbhoom
  5. BeautifulIsBetterThanUgly Logical operators Use of and, or instead of &&,

    || respectively. Though it is subjective, code seems more readable and beautiful this way. versus if valid(a) and b == 0 or s == 'yes': @myriadbhoom if(valid(a) && b == 0 || s == 'yes') {
  6. ExplicitIsBetterThanImplicit-1 Several scripting languages allow things like this: <?php $foo

    = "5"; echo $foo * 3; ?> [$]> php test.php 15% Here’s another example of Explicit is better than implicit, applied to the language itself. While Python is dynamically-typed, it is also strongly-typed. @myriadbhoom This is known as type coercion . You’ll also see it used frequently in C, where programmers often take advantage of the compiler’s lack of caring to put bits in places they don’t belong.
  7. >>> foo = "5" >>> foo * 3 '555' Adding

    them, however, >>> foo+3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects produces an exception. Tell Python that you want an integer: >>>int(foo)+3 8 Now, in Python, multiplying a string by an integer, will print the string that many times. ExplicitIsBetterThanImplicit-2 @myriadbhoom
  8. Simple is Better than Complex This aphorism follows the versus

    def gcd(x, y): while y: x, y = y, x % y return x @myriadbhoom public int gcd(int m, int n) { while (n > 0) { int r = m % n; m = n; n = r; } } Don’t make me think philosophy The Euclid’s algorithm in C and Python shows the beauty of this saying
  9. SparseIsBetterThanDense To rephrase the dictum another way, if i>0: return

    sqrt(i) elif i==0: return 0 else: return 1j * sqrt(-i) Don’t try to stick too much code on one line versus if i > 0: return sqrt(i) elif i == 0: return 0 else: return 1j * sqrt(-i) @myriadbhoom
  10. ReadabilityCounts The easy one: compare C and Python. #include <stdio.h>

    int main(void) { printf("Hello, world!\n"); return(0); } And what about indentation ? Well indented code is more readable . Thus, in Python it’s mandatory. versus print "Hello world!" @myriadbhoom
  11. ErrorsShouldNeverPassSilently A case for this aphorism. try: import this except

    ImportError: print 'this is not available' @myriadbhoom
  12. UnlessExplicitlySilenced An example for this case. try: v = d[k]

    except KeyError: v = d[k] = default @myriadbhoom
  13. InTheFaceOfAmbiguity,RefuseThe TemptationToGuess Consider: If short-circuiting doesn’t matter then I’d write

    it: if not a and b: do something What binds more tightly ‘not’ or ‘and’ ? The syntax is unambiguous , but my memory is not. Or somewhat ugly but reliable if it does: Could it be (no) ? @myriadbhoom if not(a and b): do something if b and not a: do something if (not a) and b: do something
  14. ThereShouldBeOne-andPreferably OnlyOne-obviousWayToDoIt. If you want to be proficient in C++

    (and be able to read other people’s code), you must learn them all. In Pyton you must learn only one: How many ways could you provide to “iterate over a sequence “ in C++ ? for element in sequence: And isn’t obvious ? There should be one module for every need. Iterating over an array with integers or pointers; iterating over STL vectors with various kinds of iterators … etc. @myriadbhoom
  15. AlthoughThatWayMayNotBe ObviousAtFirstUnlessYou’reDutch Ok this mostly refers to This is one

    way to do this, and it isn’t obvious at first. One of the sidebars for this is always the observation that the condition is evaluated first irrespective of the left-to-right order of the Guido van Rossum. The classic trinary if-then-else operator operands. (it’s a = cond?expr1:expr2 in C) was debated hotly. Guido came up with this: a = expr1 if cond else expr2 @myriadbhoom
  16. NowIsBetterThanNever Never: Now: f = open('i_will_stay_open_for_ages.txt', 'w') f.write('every even number

    > 2 is the sum of two primes') assert not 'this sentence is false' f.close() with open('i_will_be_closed_right_away.txt’,'w') as f: f.write('the sum of two primes > 2 is an even number’) raise AssertionError('this sentence is false') @myriadbhoom
  17. Namespaces are one honking great idea -- let’s do more

    of those! Every time you invoke a function import os print os.getcwd() instead of this from os import * print getcwd() @myriadbhoom An example for this case.
  18. Resources • https://www.slideshare.net/chirila sorina/the-zen-of-python- 53161452 • https://www.python. org/dev/peps/pep-0020/ • http://artifex.

    org/~hblanks/talks/2011/pep20_b y_example.html • https://www.quora.com/What-do- different-aphorisms-in-The-Zen- of-Python-mean @myriadbhoom