This document provides an overview of the Python programming language in under 90 minutes. It covers Python basics like Hello World, variables, data types, objects, functions, conditionals, and more. The goal is to teach readers enough Python to read, write, and understand basic Python programs in a short period of time. It also provides references to additional resources like the author's book for learning Python in more depth.
AlbaniaDreamin24 - How to easily use an API with Flows
Python Quick Start
1. 90% of Python in 90 Minutes90% of Python in 90 Minutes
@__mharrison__@__mharrison__
Copyright 2013Copyright 2013
2. About MeAbout Me
●
12+ years Python12+ years Python
●
Worked in Data Analysis, HA, Search,Worked in Data Analysis, HA, Search,
Open Source, BI, and StorageOpen Source, BI, and Storage
●
Author of multiple Python BooksAuthor of multiple Python Books
9. Three Python'isms to RememberThree Python'isms to Remember
●
dirdir
●
helphelp
●
colon/indent shufflecolon/indent shuffle
10. Why Python?Why Python?
Python is a powerful, multi-paradigm,Python is a powerful, multi-paradigm,
interpreted language popular withinterpreted language popular with
start-ups and large Co’sstart-ups and large Co’s
11. Python 2 or 3?Python 2 or 3?
For beginners there is no real differenceFor beginners there is no real difference
between Python 2 & 3. The basics are thebetween Python 2 & 3. The basics are the
same (except forsame (except for printprint))
20. Python 3 hello worldPython 3 hello world
printprint is no longer a statement, but ais no longer a statement, but a
functionfunction
print("hello world")print("hello world")
22. ObjectsObjects
Everything inEverything in PythonPython is an object that has:is an object that has:
●
anan identityidentity ((idid))
●
aa valuevalue (mutable or immutable)(mutable or immutable)
24. ValueValue
●
Mutable:Mutable:When you alter the item, theWhen you alter the item, the
idid is still the same. Dictionary, Listis still the same. Dictionary, List
●
Immutable:Immutable:String, Integer, TupleString, Integer, Tuple
40. String escaping (2)String escaping (2)
Escape Sequence Output
Backslash
' Single quote
" Double quote
b ASCII Backspace
n Newline
t Tab
u12af Unicode 16 bit
U12af89bc Unicode 32 bit
o84 Octal character
xFF Hex character
44. Whats with all theWhats with all the
'__blah__''__blah__'??
45. dunderdunder methodsmethods
dunderdunder (double under) or "special/magic"(double under) or "special/magic"
methods determine what will happenmethods determine what will happen
whenwhen ++ ((__add____add__) or) or // ((__div____div__) is) is
called.called.
46. helphelp
>>>>>> help(help("a string""a string"..startswith)startswith)
Help on built-in function startswith:Help on built-in function startswith:
startswith(...)startswith(...)
S.startswith(prefix[, start[, end]]) -> boolS.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, FalseReturn True if S starts with the specified prefix, False
otherwise.otherwise.
With optional start, test S beginning at that position.With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.prefix can also be a tuple of strings to try.
48. String methods (2)String methods (2)
●
s.index(sub)s.index(sub)
Returns index ofReturns index of subsub or exceptionor exception
●
s.join(list)s.join(list)
ReturnsReturns listlist items separated by stringitems separated by string
●
s.strip()s.strip()
Removes whitespace from start/endRemoves whitespace from start/end
62. List methods (2)List methods (2)
●
l.reverse()l.reverse()
Reverse list in placeReverse list in place
●
l.remove(item)l.remove(item)
Remove firstRemove first itemitem foundfound
●
l.pop()l.pop()
Remove/return item at end of listRemove/return item at end of list
74. whitespace (2)whitespace (2)
invokeinvoke python -ttpython -tt to error out duringto error out during
inconsistent tab/space usage in a fileinconsistent tab/space usage in a file
77. __doc____doc__
>>>>>> defdef echoecho(txt):(txt):
...... "echo back txt""echo back txt"
...... returnreturn txttxt
>>>>>> help(echo)help(echo)
Help on function echo in module __main__:Help on function echo in module __main__:
<BLANKLINE><BLANKLINE>
echo(txt)echo(txt)
echo back txtecho back txt
<BLANKLINE><BLANKLINE>
84. Boolean OperatorsBoolean Operators
andand,, oror,, notnot (for logical),(for logical), &&,, ||, and, and ^^ (for(for
bitwise)bitwise)
>>>>>> xx == 55
>>>>>> xx << -4-4 oror xx >> 44
TrueTrue
85. Boolean noteBoolean note
Parens are only required for precedenceParens are only required for precedence
ifif (x(x >> 1010):):
printprint "Big""Big"
same assame as
ifif xx >> 1010::
printprint "Big""Big"
89. rangerange notenote
Python tends to followPython tends to follow half-open intervalhalf-open interval
(([start,end)[start,end)) with) with rangerange and slices.and slices.
●
end - start = lengthend - start = length
●
easy to concat ranges w/o overlapeasy to concat ranges w/o overlap
90. iteration (2)iteration (2)
Java/C-esque style of object in arrayJava/C-esque style of object in array
access (BAD):access (BAD):
animalsanimals == [["cat""cat",, "dog""dog",, "bird""bird"]]
forfor indexindex inin rangerange((lenlen(animals)):(animals)):
printprint index, animals[index]index, animals[index]
91. iteration (3)iteration (3)
If you need indices, useIf you need indices, use enumerateenumerate
animalsanimals == [["cat""cat",, "dog""dog",, "bird""bird"]]
forfor index, valueindex, value inin enumerateenumerate(animals):(animals):
printprint index, valueindex, value
92. iteration (4)iteration (4)
CanCan breakbreak out of nearest loopout of nearest loop
forfor itemitem inin sequence:sequence:
# process until first negative# process until first negative
ifif itemitem << 00::
breakbreak
# process item# process item
93. iteration (5)iteration (5)
CanCan continuecontinue to skip over itemsto skip over items
forfor itemitem inin sequence:sequence:
ifif itemitem << 00::
continuecontinue
# process all positive items# process all positive items
94. iteration (6)iteration (6)
Can loop over lists, strings, iterators,Can loop over lists, strings, iterators,
dictionaries... sequence like things:dictionaries... sequence like things:
my_dictmy_dict == {{ "name""name":: "matt""matt",, "cash""cash":: 5.455.45}}
forfor keykey inin my_dictmy_dict..keys():keys():
# process key# process key
forfor valuevalue inin my_dictmy_dict..values():values():
# process value# process value
forfor key, valuekey, value inin my_dictmy_dict..items():items():
# process items# process items
95. passpass
passpass is a null operationis a null operation
forfor ii inin rangerange((1010):):
# do nothing 10 times# do nothing 10 times
passpass
96. HintHint
Don't modifyDon't modify listlist oror dictionarydictionary contentscontents
while looping over themwhile looping over them
98. SlicingSlicing
Sequences (lists, tuples, strings, etc) canSequences (lists, tuples, strings, etc) can
bebe slicedsliced to pull out a single itemto pull out a single item
my_petsmy_pets == [["dog""dog",, "cat""cat",, "bird""bird"]]
favoritefavorite == my_pets[my_pets[00]]
birdbird == my_pets[my_pets[-1-1]]
99. Negative IndexingNegative Indexing
Proper way to think of [negativeProper way to think of [negative
indexing] is to reinterpretindexing] is to reinterpret a[-X]a[-X] asas
a[len(a)-X]a[len(a)-X]
@gvanrossum@gvanrossum
100. Slicing (2)Slicing (2)
Slices can take an end index, to pull out aSlices can take an end index, to pull out a
list of itemslist of items
my_petsmy_pets == [["dog""dog",, "cat""cat",, "bird""bird"]]
# a list# a list
cat_and_dogcat_and_dog == my_pets[my_pets[00::22]]
cat_and_dog2cat_and_dog2 == my_pets[:my_pets[:22]]
cat_and_birdcat_and_bird == my_pets[my_pets[11::33]]
cat_and_bird2cat_and_bird2 == my_pets[my_pets[11:]:]
101. Slicing (3)Slicing (3)
Slices can take a strideSlices can take a stride
my_petsmy_pets == [["dog""dog",, "cat""cat",, "bird""bird"]]
# a list# a list
dog_and_birddog_and_bird == [[00::33::22]]
zero_three_etczero_three_etc == rangerange((00,,1010))
[::[::33]]
102. Slicing (4)Slicing (4)
Just to beat it inJust to beat it in
vegveg == "tomatoe""tomatoe"
correctcorrect == veg[:veg[:-1-1]]
tmtetmte == veg[::veg[::22]]
eotamoteotamot == veg[::veg[::-1-1]]
104. File InputFile Input
Open a file to read from it (old style):Open a file to read from it (old style):
finfin == openopen(("foo.txt""foo.txt"))
forfor lineline inin fin:fin:
# manipulate line# manipulate line
finfin..close()close()
105. File OutputFile Output
Open a file usingOpen a file using 'w''w' toto writewrite to a file:to a file:
foutfout == openopen(("bar.txt""bar.txt",, "w""w"))
foutfout..write(write("hello world""hello world"))
foutfout..close()close()
107. closing withclosing with withwith
implicitimplicit closeclose (new 2.5+ style)(new 2.5+ style)
withwith openopen(('bar.txt''bar.txt')) asas fin:fin:
forfor lineline inin fin:fin:
# process line# process line
110. Classes (2)Classes (2)
notes:notes:
●
objectobject (base class) (fixed in 3.X)(base class) (fixed in 3.X)
●
dunderdunder init (constructor)init (constructor)
●
all methods takeall methods take selfself as first parameteras first parameter
116. RememberRemember
Clean upClean up printprint statements. If you reallystatements. If you really
need them, useneed them, use logginglogging or write toor write to
sys.stdoutsys.stdout
118. pdbpdb commandscommands
●
hh - help- help
●
ss - step into- step into
●
nn - next- next
●
cc - continue- continue
●
ww - where am I (in stack)?- where am I (in stack)?
●
ll - list code around me- list code around me
119. That's allThat's all
Questions? Tweet meQuestions? Tweet me
For more details seeFor more details see
Treading on Python Volume 1Treading on Python Volume 1
@__mharrison__@__mharrison__
http://hairysun.comhttp://hairysun.com