3. >>> import this Дзэн Питона
The Zen of Python, by Tim Peters
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!
5. Hello World!
# coding: utf-8
persons = (u'Петя', u'Вася', u'Коля', u'Саша', )
# итерируем по списку
for person in persons:
print u'Привет', person
print u'done...'
$ python hello_world.py
Привет Петя
Привет Вася
Привет Коля
Привет Саша
done...
6. Hello World! v2
# coding: utf-8
"""Print greetings for the persons.
This is multiline comment."""
def greeting(person, index = None):
if index is None:
return u'Привет %s!' % person
else:
return u'%s. Привет %s!' % (index, person)
return
persons = (u'Петя', u'Вася', )
for i, person in enumerate(persons):
print greeting(person, i)
$ python hello_world2.py
0. Привет Петя!
1. Привет Вася!
7. # coding: utf-8
Hello World! v2
u"""Print greetings for the persons.
This is multiline comment."""
def greeting(person, index = None):
return u'%s. Привет %s!' % (index, person)
persons = (u'Петя', u'Вася', )
for i, person in enumerate(persons):
print greeting(person, I)
$ python
>>> import hello_world2
0. Привет Петя!
1. Привет Вася!
>>> hello_world2.greeting('Noname')
u'None. Привет Noname!'
>>> hello_world2.persons
(u'Петя', u'Вася')
>>> hello_world2.__doc__
'Print greetings for the persons.This is multiline comment.'
8. Словари
>>> # работа со структурами данных
...
>>> dict()
{}
>>> d = {'server': 'localhost', 'port': 22}
>>> pass
>>> d['server'] = '127.0.0.1'
>>> d[42] = ('Life', 'Question')
>>> d
{42: ('Life', 'Question'), 'port': 22, 'server': '127.0.0.1'}
13. Логические операции
>>> 'a' or 'b'
'a'
>>> '' or 'b'
'b'
>>> '' or [] or {}
{}
>>> True or print('Hello')
>>> True or int(noname)
>>> x = 'A' if 5 in range(10) else 'B'
>>> x
'A'
14. Средства разработки
❖ python
❖ print
❖ ipython/bpython
❖ справка
❖ автодополнение
❖ история команд и результатов
❖ pdb
❖ PyPi
❖ easy_install
❖ pip + vitrtualenv
16. Обработка исключений
try:
# Здесь код, который может вызвать исключение
raise Exception("message")
except (Тип исключения1, Тип исключения2, …), Переменная:
# Обработка исключения
raise
except (Тип исключения3, Тип исключения4, …), Переменная:
# Обработка исключения
pass
except:
# Обработка любого другого исключения
pass
else:
# Если исключения не было
pass
finally:
# Код, исполняемый в любом случае
pass