How to Think Like a Computer Scientist: Learning with Python 2nd Edition. / Как стать программистом: учимся вместе с Python. Второе издание.

→Python has a built-in doctest module for easy unit testing. Doctests can be written within a triple quoted string on the first line of the body of a function or script. They consist of sample interpreter sessions with a series of inputs to a Python prompt followed by the expected output from the Python interpreter.
0 В python есть встроенный модуль doctest предназначенный для unit-тестирования. Доктектсы в тройных кавычках могут быть написаны в начале тела функции или скрипта.
→It is a common best practice in software development these days to include automatic unit testing of source code. Unit testing provides a way to automatically verify that individual pieces of code, such as functions, are working properly. This makes it possible to change the implimentation of a function at a later time and quickly test that it still does what it was intended to do.
0 В наше время наилучшей практикой в разработке программ является включение автоматических unit-тестов в исходный код. Unit-тестирование подразумевает автоматическю проверку отдельных участков кода, таких как функции, на работоспособность. Становится возможным следить за поведением функции при изменениях кода как внутри нее, так и в самой программе.
→5.8. Unit testing with doctest
0 5.8 Unit-тесты с doctest
→>>> message = """This message will ... span several ... lines.""" >>> print message This message will span several lines. >>>
0 >>> message = """This message will
...span several
...lines."""
>>> print message
This message will
span several
lines.
>>>
→Finally, triple quoted strings can span multiple lines:
0 Наконец, тройные кавычки могут содержать многострочный текст:
→>>> print '''"Oh no", she exclaimed, "Ben's bike is broken!"''' "Oh no", she exclaimed, "Ben's bike is broken!" >>>
0 >>> print '''"Oh no", she exclaimed, "Ben's bike is broken!"'''
"Oh no", she exclaimed, "Ben's bike is broken!"
>>>
→Triple quoted strings can contain both single and double quotes inside them:
0 Тройные кавычки внутри себя могут содержать текст как с двойными так и одинарными кавычками:
→>>> type("""This is a triple quoted string using 3 double quotes.""") <type 'str'> >>> type('''This triple quoted strings uses 3 single quotes.''') <type 'str'> >>>
0 >>> type("""This is a triple quoted string using 3 double quotes.""")
<type 'str'>
>>> type('''This triple quoted strings uses 3 single quotes.''')
<type 'str'>
>>>
→In addition to the single and double quoted strings we first saw in Values and data types, Python also has triple quoted strings:
0 В добавок к одиночным и двойным кавычкам, с которыми мы познакомились раньше, python также работает с тройными кавычками:
→5.7. Triple quoted strings
0 5.7 Тройные кавычки
→use 4 spaces for indentation imports should go at the top of the file separate function definitions with two blank lines keep function definitions together keep top level statements, including function calls, together at the bottom of the program
0 - используйте 4 пробела для отступов
- импорт функций должен происходить в начале скрипта
- отделяете объявление функции двумя пустыми строками
- объявления функций должны находиться в одном месте в начале скрипта
- держите вместе выражения импорта функций, вызова функций
→We’ll have more to say about style as our programs become more complex, but a few pointers will be helpful already:
0 Мы будем больше говорить о стиле, когда наши программы станут более сложными, но несколько пунктом можно озвучить уже сейчас:
→Readability is very important to programmers, since in practice programs are read and modified far more often then they are written. All the code examples in this book will be consistent with the Python Enhancement Proposal 8 (PEP 8), a style guide developed by the Python community.
0 Удобочитаемость является очень важным параметром, на практике читать и модифицировать программы приходится гораздо чаще, чем писать. Все примеры в этой книге соответствуют Предложению по расширению python 8 (PEP 8), руговодству по стилю разработки в сообществе python.
→5.6. Programming with style
0 5.6 Программирование со стилем
→This example is a bit contrived, but we will see situations later where it is quite useful to pass a function to a function.
0 Пример, конечно, немного надуман, но вскоре мы увидим, какую пользу можно извлечь от таких комбинаций.
→15 37 3
0 15
37
3
→doto is called three times. 7 is the argument for value each time, and the functions f, g, and h are passed in for func in turn. The output of this script is:
0 Функция doto вызывается три раза. 7 - аргумент value, а функции f, g и h - аргументы func. На выходе скрипта получим:
→print doto(7, f) print doto(7, g) print doto(7, h)
0 print doto(7, f)
print doto(7, g)
print doto(7, h)
→def doto(value, func): return func(value)
0 def doto(value, func):
    return func(value)
→def h(n): return -2*n + 17
0 def h(n):
    return -2*n + 17
Резюме
Пол:
мужчина
Родной язык:
русский
С нами:
с 5 марта 2009 г. (6436 дней)
Не является членом клуба.
Деятельность:
812 версий перевода с общим рейтингом −10
1 комментарий
Карма: 2 (оценок: 2)
Написать czech личное сообщение