Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
TheZenofPython
Sorina CHIRILĂ
www.bitopedia.wordpress.com
Summary
1. History
2. The Zen of Python
3. Meaning of some of the aphorisms in The Zen of Python
4. Resources
5. Contact
pep20--thezenofpython
Author: Tim Peters
tim.peters@gmail.com
Created : 19-Aug-2004
Post history: 22-Aug-2004
Long time Py...
thezenofpython-1
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex i...
thezenofpython-2
There should be one -- and
preferably only one -- obvious way
to do it.
Although that way may not be
obvi...
beautifulisbetterthanugly
Logical operators
Use of and, or instead of &&, ||
respectively.
Though it is subjective, code s...
explicitisbetterthanimplicit-1
Every time you invoke a function
you should name its module
explicitly.
In case you forget ...
explicitisbetterthanimplicit-2
Another example: the ‘self’
parameter in methods.
You always have to mention
explicitly wha...
explicitisbetterthanimplicit-3
This is known as type coercion .
You’ll also see it used frequently
in C, where programmers...
explicitisbetterthanimplicit-4
If you really want to do so, then
you need to tell Python that, you
want an integer.
1 >>>i...
sparseisbetterthandense
To rephrase the dictum another way,
‘Don’t try to stick too much code
on one line ‘
1 if i>0: retu...
readabilitycounts
The easy one: compare C and Python.
And what about indentation ? Well
indented code is more readable .
T...
errorsshouldneverpasssilently
A case for this aphorism. 1 try:
2 import this
3 except ImportError:
4 print 'this is not av...
unlessexplicitlysilenced
An example for this case. 1 try:
2 v = d[k]
3 except KeyError:
4 v = d[k] = default
inthefaceofambiguity,refusethetemptationtoguess-1
Consider:
1 if not a and b:
2 do something
What binds more tightly ‘not’...
inthefaceofambiguity,refusethetemptationtoguess -2
This is subjective because someone
may argue that you should expect
the...
thereshouldbeone-andpreferablyonlyone-obviouswaytodoit.
(The exact contrary to The Perl
Programming Language’s motto -
the...
althoughthatwaymaynotbeobviousatfirstunlessyou’redutch
Ok this mostly refers to
Guido van Rossum.
The classic trinary if-t...
nowisbetterthannever-1
Never:
1 f = open('i_will_stay_open_for_ages.
txt', 'w')
2 f.write('every even number > 2 is the
su...
nowisbetterthannever-2
In the first example, an exception
will bump you out of the codeblock
before the file can be closed...
resources
●
● https://www.python.
org/dev/peps/pep-0020/
●
● http://artifex.
org/~hblanks/talks/2011/pep20_b
y_example.htm...
contact
E-mail:
zambetsoare at gmail.com
Upcoming SlideShare
Loading in …5
×

THE ZEN OF PYTHON

2,636 views

Published on

A presentation about good and bad ideas in coding, with examples regarding The Zen of Python.
www.bitopedia.wordpress.com

Published in: Education

THE ZEN OF PYTHON

  1. 1. TheZenofPython Sorina CHIRILĂ www.bitopedia.wordpress.com
  2. 2. Summary 1. History 2. The Zen of Python 3. Meaning of some of the aphorisms in The Zen of Python 4. Resources 5. Contact
  3. 3. pep20--thezenofpython Author: Tim Peters tim.peters@gmail.com 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.
  4. 4. 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.
  5. 5. thezenofpython-2 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.
  6. 6. beautifulisbetterthanugly Logical operators Use of and, or instead of &&, || respectively. Though it is subjective, code seems more readable and beautiful this way. 1 if (is_valid(a) && b == 0 || s == 'yes') { versus 1 if is_valid(a) and b == 0 or s == 'yes':
  7. 7. explicitisbetterthanimplicit-1 Every time you invoke a function you should name its module explicitly. In case you forget this best practice, let the last koan remind it to you: Namespaces are one honking great idea -- let’s do more of those! 1 import os 2 print os.getcwd() insted of this 1 from os import * 2 print getcwd()
  8. 8. explicitisbetterthanimplicit-2 Another example: the ‘self’ parameter in methods. You always have to mention explicitly what object you are working with. Here’s another example of Explicit is better than implicit, applied to the language itself.Whyle Python is dynamically-typed, it is also strongly-typed. Several scripting languages allow things like this: 1 <?php $foo = "5"; 2 echo $foo * 3; 3 ?> 4 [$]> php test.php 5 15% ( The % result of me not adding a new line to the end of the echo statement) (continue next slide)
  9. 9. explicitisbetterthanimplicit-3 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. Now, in Python, multiplying a string by an integer, will print the string that many times. 1 >>> foo = "5" 2 >>> foo * 3 3 '555' You’ll also see because Guido decided to override that particular operator. Adding them, however, 1 >>> foo+3 2 Traceback (most recent call last): 3 File "<input>", line 1, in <module> 4 TypeError: cannot concatenate 'str' and 'int' objects produces an exception.
  10. 10. explicitisbetterthanimplicit-4 If you really want to do so, then you need to tell Python that, you want an integer. 1 >>>int(foo)+3 2 8
  11. 11. sparseisbetterthandense To rephrase the dictum another way, ‘Don’t try to stick too much code on one line ‘ 1 if i>0: return sqrt(i) 2 elif i==0: return 0 3 else: return 1j * sqrt(-i) versus 1 if i > 0: 2 return sqrt(i) 3 elif i == 0: 4 return 0 5 else: 6 return 1j * sqrt(-i)
  12. 12. readabilitycounts The easy one: compare C and Python. And what about indentation ? Well indented code is more readable . Thus, in Python it’s mandatory. 1 #include <stdio.h> 2 int main(void) 3 { 4 printf("Hello, world!n"); 5 return(0); 6 } versus print "Hello world!"
  13. 13. errorsshouldneverpasssilently A case for this aphorism. 1 try: 2 import this 3 except ImportError: 4 print 'this is not available'
  14. 14. unlessexplicitlysilenced An example for this case. 1 try: 2 v = d[k] 3 except KeyError: 4 v = d[k] = default
  15. 15. inthefaceofambiguity,refusethetemptationtoguess-1 Consider: 1 if not a and b: 2 do something What binds more tightly ‘not’ or ‘and’ ? The syntax is unambiguous , but my memory is not. Could it be (no) ? 1 if not (a and b): 2 do something If short-circuiting doesn’t matter then I’d write it: 1 if b and not a: 2 do something Or somewhat ugly but reliable if it does: 1 if (not a) and b: 2 do something
  16. 16. inthefaceofambiguity,refusethetemptationtoguess -2 This is subjective because someone may argue that you should expect the reader of your code to know Python and thus the priorities for ‘not’ and ‘and‘, and it is not obscure enough to justify parantheses.
  17. 17. thereshouldbeone-andpreferablyonlyone-obviouswaytodoit. (The exact contrary to The Perl Programming Language’s motto - there’s more than one way to do it.) How many ways could you provide to “iterate over a sequence “ in C++ ? Iterating over an array with integers or pointers; iterating over STL vectors with various kinds of iterators … etc. 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: for element in sequence: And isn’t obvious ? There should be one module for every need.
  18. 18. althoughthatwaymaynotbeobviousatfirstunlessyou’redutch Ok this mostly refers to Guido van Rossum. The classic trinary if-then-else operator (it’s a = cond?expr1:expr2 in C) was debated hotly. Guido came up with this: a = expr1 if cond else expr2 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 operands.
  19. 19. nowisbetterthannever-1 Never: 1 f = open('i_will_stay_open_for_ages. txt', 'w') 2 f.write('every even number > 2 is the sum of two primes') 3 assert not 'this sentence is false' 4 f.close() Now: 1 with open('i_will_be_closed_right_away.txt', 'w') as f: 2 f.write('the sum of two primes > 2 is an even number') 3 raise AssertionError('this sentence is false')
  20. 20. nowisbetterthannever-2 In the first example, an exception will bump you out of the codeblock before the file can be closed. In the second, python will politely handle this for you with context managers. You could of course fix the first case by using try: and finaly: blocks, but beautiful is better than ugly.
  21. 21. resources ● ● 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
  22. 22. contact E-mail: zambetsoare at gmail.com

×