03. Красивият Python

PEP 8

This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python.

http://www.python.org/dev/peps/pep-0008/

Философия

One of Guido's key insights is that code is read much more often than it is written.

Консистентност

Когато си в Рим прави като римляните.

Изключние от правилото

When applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules.
To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean up someone else's mess (in true XP style).

Индентация

Конвенция за именуване

Какво прави този код?

       #!/usr/bin/env zhpy
       # 檔名: while.py
       數字 = 23
       運行 = 真
       當 運行
           猜測 = 整數(輸入('輸入一個數字: '))
           如果 猜測 == 數字
               印出 '恭喜, 你猜對了.'
               運行 = 假 # 這會讓循環語句結束
           假使 猜測 < 數字
               印出 '錯了, 數字再大一點.'
           否則
               印出 '錯了, 數字再小一點.'
       否則
           印出 '循環語句結束'
       印出 '結束'
    

Какво прави този код?

       #!/usr/bin/env python
       # File name: while.twpy
       number = 23
       running = True
       while running
          guess = int(raw_input('Enter an integer : '))
          if guess == number
              print 'Congratulations, you guessed it.'
              running = False # this causes the while loop to stop
          elif guess < number
              print 'No, it is higher than that.'
          else
              print 'No, it is lower than that.'
       else
          print 'The while loop is over'
       print 'Done'
    

Още за именоването...

Анонимни функции

        >>> operation = lambda x, y: x * y
        >>> print(operation(6, 7))
        42
    

Функции от по-висок ред — map

        >>> list(map(lambda x: x ** 2, range(1, 10)))
        [1, 4, 9, 16, 25, 36, 49, 64, 81]
    

Функции от по-висок ред — filter

        >>> list(filter(lambda x: x % 2, range(1, 10)))
        [1, 3, 5, 7, 9]
    

List comprehension

        [израз for променлива in поредица]

        >>> [x * x for x in range(0, 10)]
        [1, 4, 9, 16, 25, 36, 49, 64, 81]
    

List comprehension (2)

        >>> [x * x for x in range(0, 10) if x % 2]
        [1, 9, 25, 49, 81]
    

List comprehension (3)

        >>> nums = range(0, 10)
        >>> [(x, y) for x in nums for y in nums if (x + y) == 13]
        [(4, 9), (5, 8), (6, 7), (7, 6), (8, 5), (9, 4)]
    

set & dict comprehension

        >>> {x % 8 for x in range(0, 20) if (x % 2) == 0}
        {0, 2, 4, 6}

        >>> {x: x**2 for x in range(0, 5)}
        {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
    

Още въпроси?