SlideShare una empresa de Scribd logo
1 de 28
Dankook UNIV
Song Chi Young (AKA EeS)
Contect: EeS@eesguru
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!
The Zen of Python, by Tim Peters
아름다움이 추함보다 좋다.
명시가 암시보다 좋다.
단순함이 복잡함보다 좋다.
복잡함이 꼬인 것보다 좋다.
수평이 계층보다 좋다.
여유로운 것이 밀집한 것보다 좋다.
가독성은 중요하다.
특별한 경우라는 것은 규칙을 어겨야 할 정도로 특별한 것이 아니다.
허나 실용성은 순수성에 우선한다.
오류 앞에서 절대 침묵하지 말지어다.
명시적으로 오류를 감추려는 의도가 아니라면.
모호함을 앞에 두고, 이를 유추하겠다는 유혹을 버려라.
어떤 일에든 명확한 - 바람직하며 유일한 - 방법이 존재한다.
비록 그대가 우둔하여 그 방법이 처음에는 명확해 보이지 않을지라도.
지금 하는게 아예 안하는 것보다 낫다.
아예 안하는 것이 지금 *당장*보다 나을 때도 있지만.
구현 결과를 설명하기 어렵다면, 그 아이디어는 나쁘다.
구현 결과를 설명하기 쉽다면, 그 아이디어는 좋은 아이디어일 수 있다.
네임스페이스는 대박 좋은 아이디어다 -- 마구 남용해라!
Style Guide For
Python Code
• 4 spaces per indentation level.
• No hard tabs.
• Never mix tabs and spaces.
• One blank line between functions.
• Two blank lines between classes.
• Add a space after "," in dicts, lists, tuples, ETC, but not before.
• Put spaces around assignments & comparisons
•except in argument lists
• No spaces just inside parentheses or just before argument lists.
• No spaces just inside docstrings.
•joined_lower for functions, methods, attributes
•joined_lower or ALL_CAPS for constants
•StudlyCaps for classes
•camelCase only to conform to pre-existing conventions
•Attributes: interface, _internal, __private
But try to avoid the __private form. I never use it.
Trust me. If you use it, you WILL regret it later.
__private is NOT like to C++/Java private
•Keep lines below 80 characters in length
•Use implied line continuation inside parentheses/brackets/braces:
•Use backslashes as a last resort:
•Adjacent literal strings are concatenated by the parser
•Any type of quoting can be used
•r is a raw string (Backslashes are not evaluated as escapes in raw strings.)
def __init__(self, first, second, third,
fourth, fifth, sixth):
output = (first + second + third
+ fourth + fifth + sixth)
VeryLong.left_hand_side 
= even_longer.right_hand_side()
>>> print 't' r'//' """o"""
t//o
•Multiple statements on one line are a cardinal sin.
•In Python, readability counts.
•Docstrings ("""blah blah""")
= How to use code
•Comments (#blah blah)
= Why (rationale) & how code works
Idiom
Potpourri
A selection of small, useful idioms.
Now we move on to the meat of the
tutorial: lots of idioms.
We'll start with some easy ones and
work our way up.
•In Python
•The comma is the tuple constructor syntax.
•A tuple is created on the right (tuple packing).
•A tuple is the target on the left (tuple unpacking).
•Further examples of unpacking:
a, b = b, a
>>> people = (['Guido', 'BDFL', 'unlisted'])
>>> for (name, title, phone) in people:
... print name, phone
...
Guido unlisted
temp = a
a = b
b = temp
Other
language
>>> import math
>>> math.pi / 3
1.0471975511965976
>>> angle = _
>>> math.cos(angle)
0.50000000000000011
>>> _
0.50000000000000011
•_ stores the last printed expression.
•When a result is None, _ doesn't change
•This only works in the interactive interpreter
•Don't do this
•This is very inefficient
•It has terrible memory usage and performance patterns
•The join() string method does all the copying in one pass
•If you want charicter between your substrings:
•If you need to apply a function to generate the substrings
colors = ['red', 'blue', 'green', 'yellow']
result = ''
for s in colors:
result += s
result = ''.join(colors)
result = ', '.join(colors)
result = ''.join(func(i) for i in items)
•Using for with dict
•in is generally faster
•This pattern also works for items in arbitrary containers
•such as lists, tuples, and sets
•in is also an operator
Good Bad
•d.keys() creates a static list of the dictionary keys
•Otherwise, you'll get an exception
•RuntimeError: dictionary changed size during iteration
for key in d:
print key
for key in d.keys():
print key
for key in d.keys():
d[str(key)] = d[key]
navs = {}
for (portfolio, equity, position) in data:
if portfolio not in navs: navs[portfolio] = 0
navs[portfolio] += position * prices[equity]
navs = {}
for (portfolio, equity, position) in data:
navs[portfolio] = (navs.get(portfolio, 0)
+ position * prices[equity])
•We often have to initialize dictionary entries before use:
•dict.get(key, default) removes the need for the test:
•Initializing mutable dictionary values:
•dict.setdefault(key, default) does the job efficiently:
•defaultdict
equities = {}
for (portfolio, equity) in data:
if portfolio in equities:
equities[portfolio].append(equity)
else:
equities[portfolio] = [equity]
equities = defaultdict(list)
for (portfolio, equity) in data:
equities[portfolio].append(equity)
equities = {}
for (portfolio, equity) in data:
equities.setdefault(portfolio, []).append(equity)
•Building dictionaries
•Splitting dictionaries
given = ['John', 'Eric', 'Terry', 'Michael']
family = ['Cleese', 'Idle', 'Gilliam', 'Palin']
pythons = dict(zip(given, family))
>>> pprint.pprint(pythons)
{'John': 'Cleese',
'Michael': 'Palin',
'Eric': 'Idle',
'Terry': 'Gilliam'}
>>> pythons.keys()
['John', 'Michael', 'Eric', 'Terry']
>>> pythons.values()
['Cleese', 'Palin', 'Idle', 'Gilliam']
False True
False (== 0) True (== 1)
"" (empty string) any string but "" (" ", "anything")
0, 0.0 any number but 0 (1, 0.1, -1, 3.14)
[], (), {}, set() any non-empty container ([0], (None,), [''])
None almost any object that's not explicitly False
# do this: # not this:
if items: if len(items) != 0:
pass pass
# and definitely not this:
if items != []:
pass
•It's efficient to take advantage of the intrinsic truth values
Advanced
Skills
In
Python
In Other language In Python
a = 1
a = 2
b = a
Box "a" now contains an integer 1.
Now box "a" contains an integer 2.
"b" is a second box, with a
copy of integer 2.
Here, an integer 1 object has a tag labelle
Now the name "a" is attached to
an integer 2 object.
The name "b" is just a second tag
bound to the same object as "a".
•default value of a_list an empty list, is evaluated at function definition
•The correct way to get a default list (or dictionary, or set) is
to create it at run time instead, inside the function:
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
>>> print bad_append('one')
['one']
>>> print bad_append('two')
['one', 'two']
def good_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list
•Python's % operator works like C's printf function.
•By name with a dictionary
•By name using the local namespace:
name = 'David'
messages = 3
text = ('Hello %s, you have %i messages'
% (name, messages))
print text
print ('Hello %(name)s, you have %(messages)i '
'messages' % locals())
values = {'name': name, 'messages': messages}
print ('Hello %(name)s, you have %(messages)i '
'messages' % values)
•It's easy to sort a list in Python:
•We can use list's built-in sort method with a custom function:
•Sorting with keys
•You can use any existing one-argument function if applicable
def my_key(item):
return (item[1], item[3])
to_sort.sort(key=my_key)
a_list.sort()
def custom_cmp(item1, item2):
return cmp((item1[1], item1[3]),
(item2[1], item2[3]))
a_list.sort(custom_cmp)
•As a loop and As a list comprehension:
•As a generator expression:
•Use a list comprehension when a computed list is the desired end result.
•Use a generator expression when the computed list is just an intermediate step.
total = 0
for num in range(1, 101):
total += num * num
total = sum([num * num for num in range(1, 101)])
total = sum(num * num for num in range(1, 101))
month_codes = dict((fn(i+1), code)
for i, code in enumerate('FGHJKMNQUVXZ')
for fn in (int, str))
•The yield keyword turns a function into a generator.
•call a generator function, instead of running Python returns a generator object
•it has a next method. for loops just call the next method on the iterator
•A for loop can have an else clause, it is executed after the iterator runs dry
•but not after a break statement is executed.
def my_range_generator(stop):
value = 0
while value < stop:
yield value value += 1
for i in my_range_generator(10):
do_something(i)
for item in sequence:
if condition(item): break
else:
raise Exception('Condition not satisfied.')
•EAFP : Easier to ask forgiveness than permission
•LBYL: Look before you leap
•Generally EAFP is preferred, but not always.
•Duck typing
•If it walks like a duck, and talks like a duck, and looks like a duck: it's a duck
•Goose? Close enough.
•Exceptions
•Use coercion if an object must be a particular type.
•If x must be a string for your code to work, why not call
try:
return str(x)
except TypeError:
...
•To make a simultaneously importable module and executable script:
•Executed as a script though, the __name__ attribute is set to "__main__“
•Used to organize your project.
•Reduces entries in load-path.
•Reduces import name conflicts.
if __name__ == '__main__':
# script code here
package/
__init__.py
module1.py
subpackage/
__init__.py
module2.py
•Before writing any code
•Check Python's standard library.
•Check the Python Package Index (the "Cheese Shop"):
•http://cheeseshop.python.org/pypi
•Search the web. Google is your friend.
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
ubuntu@Ubuntu:~/$ sudo halt

Más contenido relacionado

La actualidad más candente

Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Pythonprimeteacher32
 
Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic OperationsWai Nwe Tun
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basicsLuigi De Russis
 
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
 
Programming with Python - Week 2
Programming with Python - Week 2Programming with Python - Week 2
Programming with Python - Week 2Ahmet Bulut
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java ProgrammersMike Bowler
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 

La actualidad más candente (18)

Go Java, Go!
Go Java, Go!Go Java, Go!
Go Java, Go!
 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Python
 
Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic Operations
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
 
Go Java, Go!
Go Java, Go!Go Java, Go!
Go Java, Go!
 
Python
PythonPython
Python
 
python.ppt
python.pptpython.ppt
python.ppt
 
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!
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Programming with Python - Week 2
Programming with Python - Week 2Programming with Python - Week 2
Programming with Python - Week 2
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
Python
PythonPython
Python
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Python language data types
Python language data typesPython language data types
Python language data types
 
python codes
python codespython codes
python codes
 

Destacado

Process coordinator in NUMA environment
Process coordinator in NUMA environmentProcess coordinator in NUMA environment
Process coordinator in NUMA environmentChiyoung Song
 
Theodore roosevelt 4
Theodore roosevelt 4Theodore roosevelt 4
Theodore roosevelt 4happyparrot
 
Limits to progressivism 6
Limits to progressivism 6Limits to progressivism 6
Limits to progressivism 6happyparrot
 
Boost Your Career as a Volunteer
Boost Your Career as a VolunteerBoost Your Career as a Volunteer
Boost Your Career as a VolunteerSarah Dalton
 
Usa in wwi 4 (6)
Usa in wwi 4 (6)Usa in wwi 4 (6)
Usa in wwi 4 (6)happyparrot
 
Stermedia profile
Stermedia profileStermedia profile
Stermedia profilestermedia
 
Limits to progressivism 6
Limits to progressivism 6Limits to progressivism 6
Limits to progressivism 6happyparrot
 
Primp Your Profile - Recruiter Edition
Primp Your Profile - Recruiter EditionPrimp Your Profile - Recruiter Edition
Primp Your Profile - Recruiter EditionSarah Dalton
 
World war i 1 (1)
World war i 1 (1)World war i 1 (1)
World war i 1 (1)happyparrot
 
HPSA Presentation for BOD Meeting 11-2014
HPSA Presentation for BOD Meeting 11-2014HPSA Presentation for BOD Meeting 11-2014
HPSA Presentation for BOD Meeting 11-2014Ginger Pierce
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonPython Ireland
 
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)Tom Lee
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
Rdio's Alex Gaynor at Heroku's Waza 2013: Why Python, Ruby and Javascript are...
Rdio's Alex Gaynor at Heroku's Waza 2013: Why Python, Ruby and Javascript are...Rdio's Alex Gaynor at Heroku's Waza 2013: Why Python, Ruby and Javascript are...
Rdio's Alex Gaynor at Heroku's Waza 2013: Why Python, Ruby and Javascript are...Heroku
 
Idioms and Idiomatic Expression
Idioms and Idiomatic ExpressionIdioms and Idiomatic Expression
Idioms and Idiomatic Expressionsnsdilfany Exo
 

Destacado (20)

Process coordinator in NUMA environment
Process coordinator in NUMA environmentProcess coordinator in NUMA environment
Process coordinator in NUMA environment
 
Theodore roosevelt 4
Theodore roosevelt 4Theodore roosevelt 4
Theodore roosevelt 4
 
Limits to progressivism 6
Limits to progressivism 6Limits to progressivism 6
Limits to progressivism 6
 
Boost Your Career as a Volunteer
Boost Your Career as a VolunteerBoost Your Career as a Volunteer
Boost Your Career as a Volunteer
 
Usa in wwi 4 (6)
Usa in wwi 4 (6)Usa in wwi 4 (6)
Usa in wwi 4 (6)
 
DrDoS
DrDoSDrDoS
DrDoS
 
React Introduction
React IntroductionReact Introduction
React Introduction
 
Stermedia profile
Stermedia profileStermedia profile
Stermedia profile
 
Limits to progressivism 6
Limits to progressivism 6Limits to progressivism 6
Limits to progressivism 6
 
Primp Your Profile - Recruiter Edition
Primp Your Profile - Recruiter EditionPrimp Your Profile - Recruiter Edition
Primp Your Profile - Recruiter Edition
 
World war i 1 (1)
World war i 1 (1)World war i 1 (1)
World war i 1 (1)
 
HPSA Presentation for BOD Meeting 11-2014
HPSA Presentation for BOD Meeting 11-2014HPSA Presentation for BOD Meeting 11-2014
HPSA Presentation for BOD Meeting 11-2014
 
Pycon 2016
Pycon 2016Pycon 2016
Pycon 2016
 
Python idioms
Python idiomsPython idioms
Python idioms
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
Python 温故
Python 温故Python 温故
Python 温故
 
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Rdio's Alex Gaynor at Heroku's Waza 2013: Why Python, Ruby and Javascript are...
Rdio's Alex Gaynor at Heroku's Waza 2013: Why Python, Ruby and Javascript are...Rdio's Alex Gaynor at Heroku's Waza 2013: Why Python, Ruby and Javascript are...
Rdio's Alex Gaynor at Heroku's Waza 2013: Why Python, Ruby and Javascript are...
 
Idioms and Idiomatic Expression
Idioms and Idiomatic ExpressionIdioms and Idiomatic Expression
Idioms and Idiomatic Expression
 

Similar a Code Like Pythonista

Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Boost Maintainability
Boost MaintainabilityBoost Maintainability
Boost MaintainabilityMosky Liu
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhioClayton Parker
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Reuven Lerner
 
Brogramming - Python, Bash for Data Processing, and Git
Brogramming - Python, Bash for Data Processing, and GitBrogramming - Python, Bash for Data Processing, and Git
Brogramming - Python, Bash for Data Processing, and GitRon Reiter
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGDSCKYAMBOGO
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : PythonRaghu Kumar
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Simplilearn
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Kel Cecil
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building BlocksCate Huston
 
Decision control units by Python.pptx includes loop, If else, list, tuple and...
Decision control units by Python.pptx includes loop, If else, list, tuple and...Decision control units by Python.pptx includes loop, If else, list, tuple and...
Decision control units by Python.pptx includes loop, If else, list, tuple and...supriyasarkar38
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptxJuanPicasso7
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingPranavSB
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Pythonyashar Aliabasi
 

Similar a Code Like Pythonista (20)

Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Boost Maintainability
Boost MaintainabilityBoost Maintainability
Boost Maintainability
 
Code with style
Code with styleCode with style
Code with style
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhio
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Brogramming - Python, Bash for Data Processing, and Git
Brogramming - Python, Bash for Data Processing, and GitBrogramming - Python, Bash for Data Processing, and Git
Brogramming - Python, Bash for Data Processing, and Git
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
 
module 2.pptx
module 2.pptxmodule 2.pptx
module 2.pptx
 
Decision control units by Python.pptx includes loop, If else, list, tuple and...
Decision control units by Python.pptx includes loop, If else, list, tuple and...Decision control units by Python.pptx includes loop, If else, list, tuple and...
Decision control units by Python.pptx includes loop, If else, list, tuple and...
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptx
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
 

Último

Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 

Último (20)

Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 

Code Like Pythonista

  • 1. Dankook UNIV Song Chi Young (AKA EeS) Contect: EeS@eesguru
  • 2. 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!
  • 3. The Zen of Python, by Tim Peters 아름다움이 추함보다 좋다. 명시가 암시보다 좋다. 단순함이 복잡함보다 좋다. 복잡함이 꼬인 것보다 좋다. 수평이 계층보다 좋다. 여유로운 것이 밀집한 것보다 좋다. 가독성은 중요하다. 특별한 경우라는 것은 규칙을 어겨야 할 정도로 특별한 것이 아니다. 허나 실용성은 순수성에 우선한다. 오류 앞에서 절대 침묵하지 말지어다. 명시적으로 오류를 감추려는 의도가 아니라면. 모호함을 앞에 두고, 이를 유추하겠다는 유혹을 버려라. 어떤 일에든 명확한 - 바람직하며 유일한 - 방법이 존재한다. 비록 그대가 우둔하여 그 방법이 처음에는 명확해 보이지 않을지라도. 지금 하는게 아예 안하는 것보다 낫다. 아예 안하는 것이 지금 *당장*보다 나을 때도 있지만. 구현 결과를 설명하기 어렵다면, 그 아이디어는 나쁘다. 구현 결과를 설명하기 쉽다면, 그 아이디어는 좋은 아이디어일 수 있다. 네임스페이스는 대박 좋은 아이디어다 -- 마구 남용해라!
  • 5. • 4 spaces per indentation level. • No hard tabs. • Never mix tabs and spaces. • One blank line between functions. • Two blank lines between classes. • Add a space after "," in dicts, lists, tuples, ETC, but not before. • Put spaces around assignments & comparisons •except in argument lists • No spaces just inside parentheses or just before argument lists. • No spaces just inside docstrings.
  • 6. •joined_lower for functions, methods, attributes •joined_lower or ALL_CAPS for constants •StudlyCaps for classes •camelCase only to conform to pre-existing conventions •Attributes: interface, _internal, __private But try to avoid the __private form. I never use it. Trust me. If you use it, you WILL regret it later. __private is NOT like to C++/Java private
  • 7. •Keep lines below 80 characters in length •Use implied line continuation inside parentheses/brackets/braces: •Use backslashes as a last resort: •Adjacent literal strings are concatenated by the parser •Any type of quoting can be used •r is a raw string (Backslashes are not evaluated as escapes in raw strings.) def __init__(self, first, second, third, fourth, fifth, sixth): output = (first + second + third + fourth + fifth + sixth) VeryLong.left_hand_side = even_longer.right_hand_side() >>> print 't' r'//' """o""" t//o
  • 8. •Multiple statements on one line are a cardinal sin. •In Python, readability counts. •Docstrings ("""blah blah""") = How to use code •Comments (#blah blah) = Why (rationale) & how code works
  • 9. Idiom Potpourri A selection of small, useful idioms. Now we move on to the meat of the tutorial: lots of idioms. We'll start with some easy ones and work our way up.
  • 10. •In Python •The comma is the tuple constructor syntax. •A tuple is created on the right (tuple packing). •A tuple is the target on the left (tuple unpacking). •Further examples of unpacking: a, b = b, a >>> people = (['Guido', 'BDFL', 'unlisted']) >>> for (name, title, phone) in people: ... print name, phone ... Guido unlisted temp = a a = b b = temp Other language
  • 11. >>> import math >>> math.pi / 3 1.0471975511965976 >>> angle = _ >>> math.cos(angle) 0.50000000000000011 >>> _ 0.50000000000000011 •_ stores the last printed expression. •When a result is None, _ doesn't change •This only works in the interactive interpreter
  • 12. •Don't do this •This is very inefficient •It has terrible memory usage and performance patterns •The join() string method does all the copying in one pass •If you want charicter between your substrings: •If you need to apply a function to generate the substrings colors = ['red', 'blue', 'green', 'yellow'] result = '' for s in colors: result += s result = ''.join(colors) result = ', '.join(colors) result = ''.join(func(i) for i in items)
  • 13. •Using for with dict •in is generally faster •This pattern also works for items in arbitrary containers •such as lists, tuples, and sets •in is also an operator Good Bad •d.keys() creates a static list of the dictionary keys •Otherwise, you'll get an exception •RuntimeError: dictionary changed size during iteration for key in d: print key for key in d.keys(): print key for key in d.keys(): d[str(key)] = d[key]
  • 14. navs = {} for (portfolio, equity, position) in data: if portfolio not in navs: navs[portfolio] = 0 navs[portfolio] += position * prices[equity] navs = {} for (portfolio, equity, position) in data: navs[portfolio] = (navs.get(portfolio, 0) + position * prices[equity]) •We often have to initialize dictionary entries before use: •dict.get(key, default) removes the need for the test:
  • 15. •Initializing mutable dictionary values: •dict.setdefault(key, default) does the job efficiently: •defaultdict equities = {} for (portfolio, equity) in data: if portfolio in equities: equities[portfolio].append(equity) else: equities[portfolio] = [equity] equities = defaultdict(list) for (portfolio, equity) in data: equities[portfolio].append(equity) equities = {} for (portfolio, equity) in data: equities.setdefault(portfolio, []).append(equity)
  • 16. •Building dictionaries •Splitting dictionaries given = ['John', 'Eric', 'Terry', 'Michael'] family = ['Cleese', 'Idle', 'Gilliam', 'Palin'] pythons = dict(zip(given, family)) >>> pprint.pprint(pythons) {'John': 'Cleese', 'Michael': 'Palin', 'Eric': 'Idle', 'Terry': 'Gilliam'} >>> pythons.keys() ['John', 'Michael', 'Eric', 'Terry'] >>> pythons.values() ['Cleese', 'Palin', 'Idle', 'Gilliam']
  • 17. False True False (== 0) True (== 1) "" (empty string) any string but "" (" ", "anything") 0, 0.0 any number but 0 (1, 0.1, -1, 3.14) [], (), {}, set() any non-empty container ([0], (None,), ['']) None almost any object that's not explicitly False # do this: # not this: if items: if len(items) != 0: pass pass # and definitely not this: if items != []: pass •It's efficient to take advantage of the intrinsic truth values
  • 19. In Other language In Python a = 1 a = 2 b = a Box "a" now contains an integer 1. Now box "a" contains an integer 2. "b" is a second box, with a copy of integer 2. Here, an integer 1 object has a tag labelle Now the name "a" is attached to an integer 2 object. The name "b" is just a second tag bound to the same object as "a".
  • 20. •default value of a_list an empty list, is evaluated at function definition •The correct way to get a default list (or dictionary, or set) is to create it at run time instead, inside the function: def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_list >>> print bad_append('one') ['one'] >>> print bad_append('two') ['one', 'two'] def good_append(new_item, a_list=None): if a_list is None: a_list = [] a_list.append(new_item) return a_list
  • 21. •Python's % operator works like C's printf function. •By name with a dictionary •By name using the local namespace: name = 'David' messages = 3 text = ('Hello %s, you have %i messages' % (name, messages)) print text print ('Hello %(name)s, you have %(messages)i ' 'messages' % locals()) values = {'name': name, 'messages': messages} print ('Hello %(name)s, you have %(messages)i ' 'messages' % values)
  • 22. •It's easy to sort a list in Python: •We can use list's built-in sort method with a custom function: •Sorting with keys •You can use any existing one-argument function if applicable def my_key(item): return (item[1], item[3]) to_sort.sort(key=my_key) a_list.sort() def custom_cmp(item1, item2): return cmp((item1[1], item1[3]), (item2[1], item2[3])) a_list.sort(custom_cmp)
  • 23. •As a loop and As a list comprehension: •As a generator expression: •Use a list comprehension when a computed list is the desired end result. •Use a generator expression when the computed list is just an intermediate step. total = 0 for num in range(1, 101): total += num * num total = sum([num * num for num in range(1, 101)]) total = sum(num * num for num in range(1, 101)) month_codes = dict((fn(i+1), code) for i, code in enumerate('FGHJKMNQUVXZ') for fn in (int, str))
  • 24. •The yield keyword turns a function into a generator. •call a generator function, instead of running Python returns a generator object •it has a next method. for loops just call the next method on the iterator •A for loop can have an else clause, it is executed after the iterator runs dry •but not after a break statement is executed. def my_range_generator(stop): value = 0 while value < stop: yield value value += 1 for i in my_range_generator(10): do_something(i) for item in sequence: if condition(item): break else: raise Exception('Condition not satisfied.')
  • 25. •EAFP : Easier to ask forgiveness than permission •LBYL: Look before you leap •Generally EAFP is preferred, but not always. •Duck typing •If it walks like a duck, and talks like a duck, and looks like a duck: it's a duck •Goose? Close enough. •Exceptions •Use coercion if an object must be a particular type. •If x must be a string for your code to work, why not call try: return str(x) except TypeError: ...
  • 26. •To make a simultaneously importable module and executable script: •Executed as a script though, the __name__ attribute is set to "__main__“ •Used to organize your project. •Reduces entries in load-path. •Reduces import name conflicts. if __name__ == '__main__': # script code here package/ __init__.py module1.py subpackage/ __init__.py module2.py
  • 27. •Before writing any code •Check Python's standard library. •Check the Python Package Index (the "Cheese Shop"): •http://cheeseshop.python.org/pypi •Search the web. Google is your friend.
  • 28. Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> exit Use exit() or Ctrl-D (i.e. EOF) to exit >>> exit() ubuntu@Ubuntu:~/$ sudo halt

Notas del editor

  1. Ref : http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html https://docs.python.org/27/