SlideShare a Scribd company logo
Python: легко и просто.
Красиво решаем повседневные задачи.
Александр Семенюк
a_semianiuk@wargaming.net
Python делает всё, чтобы упростить вашу жизнь.
Этот язык предоставляет многообразие инструментов,
позволяющих легко решать многие задачи.
if len(mylist) == 0:
raise Exception('Empty list is not acceptable')
>>> bool( 0 )
False
>>> bool( [] )
False
>>> bool( {} )
False
>>> bool( None )
False
>>> bool( '' )
False
if mylist:
raise Exception('Empty list is not acceptable')
class Basket(object):
empty = True
items = []
def __nonzero__(self):
return not self.empty
def __len__(self):
return len(self.items)
basket = Basket()
print bool(basket) # False
if mylist == None:
do_something()
if mylist == None:
do_something()
if mylist is None:
do_something()
$ python -m timeit -s "x = None" "x is None"
10000000 loops, best of 3: 0.0329 usec per loop
$ python -m timeit -s "x = None" "x == None"
10000000 loops, best of 3: 0.0607 usec per loop
• Всё в Python – это объект.
• Каждая переменная – ссылка на объект.
• Оператор is сравнивает эти ссылки.
class A:
pass
a = A()
b = a
print a is b
print id(a)
print id(b)
True
33274616
33274616
• В Python есть неизменяемые объекты. Их значение не меняется
после создания:
• Числа - 0, 245, 10000000000000001
• Строки - 'Hi people!'
• Кортежи (неизменяемые списки) - (1,2, 'a')
• И, конечно же, None !
if mylist:
raise Exception('Empty list is not acceptable')
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
…
class EmptyListError(Exception):
pass
if not mylist:
raise EmptyListError('Empty list is not acceptable')
try:
work_with_list([])
except EmptyListError:
# we know what's wrong
try:
work_with_list([])
except Exception:
# what to do?
• Python знает, где истина.
• ‘is None’ лучше, чем ‘== None’.
• Всё объект!
• Создавать свои собственные исключения круто.
try:
f = open('config.txt')
line = f.readline()
while line:
line = line.strip(' n')
if not line:
continue
if line.startswith('#'):
continue
do_some_staff(line)
line = f.readline()
finally:
f.close()
for i in range(len(mylist)):
print mylist[i]
for i in range(len(mylist)):
print mylist[i]
for item in mylist:
print item
import itertools
for i in itertools.count():
print i
for item in reversed(mylist):
print item
for item in reversed(mylist):
print item
>>> mylist = [1,2,3]
>>> mylist[::-1]
[3, 2, 1]
$ python -m timeit -s "l = [1, 2, 3]" "list(reversed(l))"
1000000 loops, best of 3: 0.995 usec per loop
$ python -m timeit -s "l = [1, 2, 3]" "l[::-1]"
1000000 loops, best of 3: 0.202 usec per loop
$ python -m timeit -s "l = [1, 2, 3]" "for i in reversed(l): pass"
1000000 loops, best of 3: 0.28 usec per loop
$ python -m timeit -s "l = [1, 2, 3]" "for i in l[::-1]: pass"
1000000 loops, best of 3: 0.318 usec per loop
heroes = ['Batman', 'Spiderman', 'Hulk', 'Invisible Woman']
colors = ['black', 'red', 'green']
for i in range(min(len(heroes), len(colors)):
print list1[i], 'is', list2[i]
for hero, color in zip(heroes, colors):
print hero, 'is', color
heroes_with_colors = dict(zip(heroes, colors))
print heroes_with_colors
{
'Spiderman': 'red',
'Batman': 'black',
'Hulk': 'green'
}
from itertools import izip
for hero, color in izip(heroes, colors):
print hero, 'is', color
>>> for i in 'python': i
...
'p'
'y'
't'
'h'
'o'
'n'
>>> for i in 'python': i
...
'p'
'y'
't'
'h'
'o'
'n'
>>> for key in heroes_with_colors: key
...
'Spiderman'
'Batman'
'Hulk'
>>> for i in 'python': i
...
'p'
'y'
't'
'h'
'o'
'n'
>>> for key in heroes_with_colors: key
...
'Spiderman'
'Batman'
'Hulk'
>>> import re
>>> for match in re.finditer(pattern, string):
... # each match in the string
...
>>> for line in myfile:
... print repr(line) # each line in a file
...
f = open('config.txt')
try:
for line in f:
line = line.strip(' n')
if not line:
continue
if line.startswith('#'):
continue
do_some_staff(line)
finally:
f.close()
def iterate_lines(f):
for line in f:
line = line.strip(' n')
if not line:
continue
if line.startswith('#'):
continue
yield line
f = open('config.txt')
try:
for line in iterate_lines(f):
do_some_staff(line)
finally:
f.close()
>>> mylist
['a', 'b', 'b', 'c']
>>> for index, item in enumerate(mylist):
... if item == 'b':
... del mylist[index]
...
>>> mylist
['a', 'b', 'c']
>>> mydict
{'b': 2}
>>> for key in mydict:
... if key == 'b':
... del mydict[key]
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
>>> for key in mydict.keys():
... if key == 'b':
... del mydict[key]
...
>>> mydict
{}
f = open('config.txt')
try:
for line in iterate_lines(f):
do_some_staff(line)
finally:
f.close()
with EXPR as VAR:
BLOCK
with open('config.txt') as f:
process_file(f)
try:
dangerous_actions()
except AttributeError:
pass # we don't care
from contextlib import contextmanager
@contextmanager
def ignore_errors(*errors):
try:
yield
except errors:
pass
>>> with ignore_errors(KeyError, AttributeError):
... raise KeyError
...
>>>
with open('config.txt') as f:
for line in iterate_lines(f):
do_some_staff(line)
• Итерируйтесь правильно
• Отделяйте административную логику от бизнес логики
• Не изменяйте список, по которому итерируетесь
• Контекстные менеджеры молодцы
Большое спасибо за внимание!

More Related Content

What's hot

Baabtra.com little coder chapter - 4
Baabtra.com little coder   chapter - 4Baabtra.com little coder   chapter - 4
Baabtra.com little coder chapter - 4
baabtra.com - No. 1 supplier of quality freshers
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
Marc Gouw
 
프알못의 Keras 사용기
프알못의 Keras 사용기프알못의 Keras 사용기
프알못의 Keras 사용기
Mijeong Jeon
 
iOS와 케라스의 만남
iOS와 케라스의 만남iOS와 케라스의 만남
iOS와 케라스의 만남
Mijeong Jeon
 
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
Phillip Trelford
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
Programação Assíncrona com Kotlin Coroutines
Programação Assíncrona com Kotlin CoroutinesProgramação Assíncrona com Kotlin Coroutines
Programação Assíncrona com Kotlin Coroutines
Lucas Borsatto
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
Iccha Sethi
 
Recursive implicit proofs with Shapeless HLists
Recursive implicit proofs with Shapeless HListsRecursive implicit proofs with Shapeless HLists
Recursive implicit proofs with Shapeless HLists
Vladimir Pavkin
 
From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pyside
Dinesh Manajipet
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
Ahmad Hussein
 
Fizz and buzz of computer programs in python.
Fizz and buzz of computer programs in python.Fizz and buzz of computer programs in python.
Fizz and buzz of computer programs in python.
Esehara Shigeo
 
Joshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages TodayJoshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages TodayRefresh Events
 
2 × 3 = 6
2 × 3 = 62 × 3 = 6
2 × 3 = 6
Tzu-ping Chung
 
Sequence Types in Python Programming
Sequence Types in Python ProgrammingSequence Types in Python Programming
Sequence Types in Python Programming
Bobby Murugesan
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
Mohammed Saleh
 
Random And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python CgiRandom And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python CgiAkramWaseem
 

What's hot (20)

Baabtra.com little coder chapter - 4
Baabtra.com little coder   chapter - 4Baabtra.com little coder   chapter - 4
Baabtra.com little coder chapter - 4
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
 
프알못의 Keras 사용기
프알못의 Keras 사용기프알못의 Keras 사용기
프알못의 Keras 사용기
 
iOS와 케라스의 만남
iOS와 케라스의 만남iOS와 케라스의 만남
iOS와 케라스의 만남
 
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
 
Python programming
Python  programmingPython  programming
Python programming
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Programação Assíncrona com Kotlin Coroutines
Programação Assíncrona com Kotlin CoroutinesProgramação Assíncrona com Kotlin Coroutines
Programação Assíncrona com Kotlin Coroutines
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
Recursive implicit proofs with Shapeless HLists
Recursive implicit proofs with Shapeless HListsRecursive implicit proofs with Shapeless HLists
Recursive implicit proofs with Shapeless HLists
 
From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pyside
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
 
Implode & Explode in PHP
Implode & Explode in PHPImplode & Explode in PHP
Implode & Explode in PHP
 
Fizz and buzz of computer programs in python.
Fizz and buzz of computer programs in python.Fizz and buzz of computer programs in python.
Fizz and buzz of computer programs in python.
 
Joshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages TodayJoshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages Today
 
2 × 3 = 6
2 × 3 = 62 × 3 = 6
2 × 3 = 6
 
Sequence Types in Python Programming
Sequence Types in Python ProgrammingSequence Types in Python Programming
Sequence Types in Python Programming
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
Random And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python CgiRandom And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python Cgi
 

Viewers also liked

Breakfast forward2013kevinmurphy
Breakfast forward2013kevinmurphyBreakfast forward2013kevinmurphy
Breakfast forward2013kevinmurphykgbmurphy
 
Fabric для управления серверами
Fabric для управления серверамиFabric для управления серверами
Fabric для управления серверами
Maxim Kulsha
 
Physical is the new digital
Physical is the new digitalPhysical is the new digital
Physical is the new digitalkgbmurphy
 
World tourism asia&europe
World tourism   asia&europeWorld tourism   asia&europe
World tourism asia&europe
Health & Beauty
 
Branded Entertainment in Asia
Branded Entertainment in AsiaBranded Entertainment in Asia
Branded Entertainment in Asia
Ian Stewart
 
Asia Entertainment & Resorts Nov. 2009 Investor Presentation
Asia Entertainment & Resorts Nov. 2009 Investor PresentationAsia Entertainment & Resorts Nov. 2009 Investor Presentation
Asia Entertainment & Resorts Nov. 2009 Investor Presentation
GeoInvesting LLC
 

Viewers also liked (6)

Breakfast forward2013kevinmurphy
Breakfast forward2013kevinmurphyBreakfast forward2013kevinmurphy
Breakfast forward2013kevinmurphy
 
Fabric для управления серверами
Fabric для управления серверамиFabric для управления серверами
Fabric для управления серверами
 
Physical is the new digital
Physical is the new digitalPhysical is the new digital
Physical is the new digital
 
World tourism asia&europe
World tourism   asia&europeWorld tourism   asia&europe
World tourism asia&europe
 
Branded Entertainment in Asia
Branded Entertainment in AsiaBranded Entertainment in Asia
Branded Entertainment in Asia
 
Asia Entertainment & Resorts Nov. 2009 Investor Presentation
Asia Entertainment & Resorts Nov. 2009 Investor PresentationAsia Entertainment & Resorts Nov. 2009 Investor Presentation
Asia Entertainment & Resorts Nov. 2009 Investor Presentation
 

Similar to Python легко и просто. Красиво решаем повседневные задачи

Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfpython3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
info706022
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadies
Alicia Pérez
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
beginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxbeginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptx
HongAnhNguyn285885
 
python codes
python codespython codes
python codes
tusharpanda88
 
Beginner's Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet.pdfBeginner's Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet.pdf
AkhileshKumar436707
 
cover every basics of python with this..
cover every basics of python with this..cover every basics of python with this..
cover every basics of python with this..
karkimanish411
 
Arrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowArrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com Arrow
Leandro Ferreira
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
Inzamam Baig
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Matt Harrison
 
ECE-PYTHON.docx
ECE-PYTHON.docxECE-PYTHON.docx
ECE-PYTHON.docx
Chaithanya89350
 
Python
PythonPython
Python
대갑 김
 
Practical File Grade 12.pdf
Practical File Grade 12.pdfPractical File Grade 12.pdf
Practical File Grade 12.pdf
dipanshujoshi8869
 
Function in Python [Autosaved].ppt
Function in Python [Autosaved].pptFunction in Python [Autosaved].ppt
Function in Python [Autosaved].ppt
GaganvirKaur
 
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docximport os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
Blake0FxCampbelld
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
NawalKishore38
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
Paige Bailey
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
gsterndale
 

Similar to Python легко и просто. Красиво решаем повседневные задачи (20)

Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfpython3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadies
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
beginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxbeginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptx
 
python codes
python codespython codes
python codes
 
Beginner's Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet.pdfBeginner's Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet.pdf
 
cover every basics of python with this..
cover every basics of python with this..cover every basics of python with this..
cover every basics of python with this..
 
Arrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowArrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com Arrow
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
ECE-PYTHON.docx
ECE-PYTHON.docxECE-PYTHON.docx
ECE-PYTHON.docx
 
Python
PythonPython
Python
 
Practical File Grade 12.pdf
Practical File Grade 12.pdfPractical File Grade 12.pdf
Practical File Grade 12.pdf
 
Function in Python [Autosaved].ppt
Function in Python [Autosaved].pptFunction in Python [Autosaved].ppt
Function in Python [Autosaved].ppt
 
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docximport os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 

Recently uploaded

The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
gb193092
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 

Recently uploaded (20)

The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 

Python легко и просто. Красиво решаем повседневные задачи

  • 1.
  • 2. Python: легко и просто. Красиво решаем повседневные задачи. Александр Семенюк a_semianiuk@wargaming.net
  • 3. Python делает всё, чтобы упростить вашу жизнь. Этот язык предоставляет многообразие инструментов, позволяющих легко решать многие задачи.
  • 4. if len(mylist) == 0: raise Exception('Empty list is not acceptable')
  • 5. >>> bool( 0 ) False >>> bool( [] ) False >>> bool( {} ) False >>> bool( None ) False >>> bool( '' ) False
  • 6. if mylist: raise Exception('Empty list is not acceptable')
  • 7. class Basket(object): empty = True items = [] def __nonzero__(self): return not self.empty def __len__(self): return len(self.items) basket = Basket() print bool(basket) # False
  • 8. if mylist == None: do_something()
  • 9. if mylist == None: do_something() if mylist is None: do_something()
  • 10. $ python -m timeit -s "x = None" "x is None" 10000000 loops, best of 3: 0.0329 usec per loop $ python -m timeit -s "x = None" "x == None" 10000000 loops, best of 3: 0.0607 usec per loop
  • 11. • Всё в Python – это объект. • Каждая переменная – ссылка на объект. • Оператор is сравнивает эти ссылки. class A: pass a = A() b = a print a is b print id(a) print id(b) True 33274616 33274616
  • 12. • В Python есть неизменяемые объекты. Их значение не меняется после создания: • Числа - 0, 245, 10000000000000001 • Строки - 'Hi people!' • Кортежи (неизменяемые списки) - (1,2, 'a') • И, конечно же, None !
  • 13. if mylist: raise Exception('Empty list is not acceptable')
  • 14. BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StandardError | +-- BufferError | +-- ArithmeticError | | +-- FloatingPointError | | +-- OverflowError | | +-- ZeroDivisionError …
  • 15. class EmptyListError(Exception): pass if not mylist: raise EmptyListError('Empty list is not acceptable')
  • 16. try: work_with_list([]) except EmptyListError: # we know what's wrong try: work_with_list([]) except Exception: # what to do?
  • 17. • Python знает, где истина. • ‘is None’ лучше, чем ‘== None’. • Всё объект! • Создавать свои собственные исключения круто.
  • 18. try: f = open('config.txt') line = f.readline() while line: line = line.strip(' n') if not line: continue if line.startswith('#'): continue do_some_staff(line) line = f.readline() finally: f.close()
  • 19. for i in range(len(mylist)): print mylist[i]
  • 20. for i in range(len(mylist)): print mylist[i] for item in mylist: print item
  • 21. import itertools for i in itertools.count(): print i
  • 22. for item in reversed(mylist): print item
  • 23. for item in reversed(mylist): print item >>> mylist = [1,2,3] >>> mylist[::-1] [3, 2, 1]
  • 24. $ python -m timeit -s "l = [1, 2, 3]" "list(reversed(l))" 1000000 loops, best of 3: 0.995 usec per loop $ python -m timeit -s "l = [1, 2, 3]" "l[::-1]" 1000000 loops, best of 3: 0.202 usec per loop
  • 25. $ python -m timeit -s "l = [1, 2, 3]" "for i in reversed(l): pass" 1000000 loops, best of 3: 0.28 usec per loop $ python -m timeit -s "l = [1, 2, 3]" "for i in l[::-1]: pass" 1000000 loops, best of 3: 0.318 usec per loop
  • 26. heroes = ['Batman', 'Spiderman', 'Hulk', 'Invisible Woman'] colors = ['black', 'red', 'green'] for i in range(min(len(heroes), len(colors)): print list1[i], 'is', list2[i]
  • 27. for hero, color in zip(heroes, colors): print hero, 'is', color
  • 28. heroes_with_colors = dict(zip(heroes, colors)) print heroes_with_colors { 'Spiderman': 'red', 'Batman': 'black', 'Hulk': 'green' }
  • 29. from itertools import izip for hero, color in izip(heroes, colors): print hero, 'is', color
  • 30. >>> for i in 'python': i ... 'p' 'y' 't' 'h' 'o' 'n'
  • 31. >>> for i in 'python': i ... 'p' 'y' 't' 'h' 'o' 'n' >>> for key in heroes_with_colors: key ... 'Spiderman' 'Batman' 'Hulk'
  • 32. >>> for i in 'python': i ... 'p' 'y' 't' 'h' 'o' 'n' >>> for key in heroes_with_colors: key ... 'Spiderman' 'Batman' 'Hulk' >>> import re >>> for match in re.finditer(pattern, string): ... # each match in the string ...
  • 33. >>> for line in myfile: ... print repr(line) # each line in a file ...
  • 34. f = open('config.txt') try: for line in f: line = line.strip(' n') if not line: continue if line.startswith('#'): continue do_some_staff(line) finally: f.close()
  • 35. def iterate_lines(f): for line in f: line = line.strip(' n') if not line: continue if line.startswith('#'): continue yield line
  • 36. f = open('config.txt') try: for line in iterate_lines(f): do_some_staff(line) finally: f.close()
  • 37. >>> mylist ['a', 'b', 'b', 'c'] >>> for index, item in enumerate(mylist): ... if item == 'b': ... del mylist[index] ... >>> mylist ['a', 'b', 'c']
  • 38. >>> mydict {'b': 2} >>> for key in mydict: ... if key == 'b': ... del mydict[key] ... Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: dictionary changed size during iteration
  • 39. >>> for key in mydict.keys(): ... if key == 'b': ... del mydict[key] ... >>> mydict {}
  • 40. f = open('config.txt') try: for line in iterate_lines(f): do_some_staff(line) finally: f.close()
  • 41. with EXPR as VAR: BLOCK
  • 42. with open('config.txt') as f: process_file(f)
  • 44. from contextlib import contextmanager @contextmanager def ignore_errors(*errors): try: yield except errors: pass
  • 45. >>> with ignore_errors(KeyError, AttributeError): ... raise KeyError ... >>>
  • 46. with open('config.txt') as f: for line in iterate_lines(f): do_some_staff(line)
  • 47. • Итерируйтесь правильно • Отделяйте административную логику от бизнес логики • Не изменяйте список, по которому итерируетесь • Контекстные менеджеры молодцы