SlideShare a Scribd company logo
1 of 48
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

Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: FunctionsMarc 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 2015Phillip Trelford
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanWei-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 CoroutinesLucas Borsatto
 
Recursive implicit proofs with Shapeless HLists
Recursive implicit proofs with Shapeless HListsRecursive implicit proofs with Shapeless HLists
Recursive implicit proofs with Shapeless HListsVladimir 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 pysideDinesh Manajipet
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2Ahmad 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
 
Sequence Types in Python Programming
Sequence Types in Python ProgrammingSequence Types in Python Programming
Sequence Types in Python ProgrammingBobby Murugesan
 
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&europeHealth & Beauty
 
Branded Entertainment in Asia
Branded Entertainment in AsiaBranded Entertainment in Asia
Branded Entertainment in AsiaIan 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 PresentationGeoInvesting 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 WayUtkarsh Sengar
 
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfpython3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfinfo706022
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadiesAlicia Pérez
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
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).pptxHongAnhNguyn285885
 
Beginner's Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet.pdfBeginner's Python Cheat Sheet.pdf
Beginner's Python Cheat Sheet.pdfAkhileshKumar436707
 
Arrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowArrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowLeandro Ferreira
 
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 MinutesMatt Harrison
 
Function in Python [Autosaved].ppt
Function in Python [Autosaved].pptFunction in Python [Autosaved].ppt
Function in Python [Autosaved].pptGaganvirKaur
 
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.docxBlake0FxCampbelld
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptxNawalKishore38
 
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 bossgsterndale
 

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
 
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
 
1 the ruby way
1   the ruby way1   the ruby way
1 the ruby way
 

Recently uploaded

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 

Recently uploaded (20)

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 

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. • Итерируйтесь правильно • Отделяйте административную логику от бизнес логики • Не изменяйте список, по которому итерируетесь • Контекстные менеджеры молодцы