SlideShare a Scribd company logo
1 of 21
Larry cai <larry.caiyu@gmail.com>
 What is python ? Why Python ?
 Exercise 1: Hello World
 Exercise 2: String, List via command line
 Exercise 3: For loop with if..else..
 Exercise 4: Learn how to use module json to dump data
 Exercise 5: Generate online NASDAQ data using json
!!! Lots of materials are copied from
http://www.cs.columbia.edu/~hgs/teaching/ap/slides/python.ppt and which is
based on official tutorial by Guido van Rossum
Exercises are created by Larry Cai
Python in 90 minutes2
What is Python ? And Why Python 2.7
 Python is an easy to learn, powerful script programming
language
 Python is mature and better community compare to Perl
 Python is high level over shell script
 Python is well supported in OS as default compare to
Ruby (which is also nice)
 Python 3.x is quite new, not well accepted
 Welcome to Python world
Python in 90 minutes3
 Python 2.7.x In Windows with Git Bash
 http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi
 Add into Path
 How to run ?
 /usr/local/bin/python
 #!/usr/bin/env python
 interactive use
Python 2.7.3 (default,Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
 $ python script.py
Python in 90 minutes4
 Hello World
 hello.py
#!/usr/bin/env python
for name in [“larry”,”cai”]:
print "hello" , name
Python in 90 minutes5
Tips: Indent is important for python
 Visible symbol in your favorite editor
Python in 90 minutes6
Python forces to use a certainPython forces to use a certain
indentation style instead of “{,}”indentation style instead of “{,}”
Basic operations & program
 Assignment:
 size = 40
 a = b = c = 3
 Numbers
 integer, float
 complex numbers: 1j+3,
abs(z)
 Strings
 'hello world',
'it's hot'
 "bye world"
 continuation via  or use """
long text """"
a,b = 0, 1
# non-zero = true
while b < 10:
# formatted output,
without n
print b,
# multiple assignment
a,b = b, a+b
Python in 90 minutes7
String & List operations
 concatenate with + or
neighbors
 word = 'Help' + x
 word = 'Help' 'a'
 subscripting of strings
 'Hello'[2]  'l'
 slice: 'Hello'[1:2]  'el'
 word[-1]  last character
 len(word)  5
 immutable: cannot assign to
subscript
 lists can be heterogeneous
 a = ['spam', 'eggs',
100, 1234, 2*2]
 Lists can be indexed and
sliced:
 a[0]  spam
 a[:2]  ['spam', 'eggs']
 Lists can be manipulated
 a[2] = a[2] + 23
 a[0:2] = [1,12]
 a[0:0] = []
 len(a)  5
Python in 90 minutes8
Learn the standard script sample
https://gist.github.com/4308811
Help doc
Import library
Function
Main func
Start here !
Python in 90 minutes9
Exercise 2: remove characters
 Practices basic operation in Interactive Shell
 Add features to remove two characters each from input
 ./hello2.py -m larry,cai
hello rry
hello i
Hints: nameHints: names = messages.split(“,”)s = messages.split(“,”)
Python in 90 minutes10
Control flow: if & for
x =
int(raw_input("Please
enter #:"))
if x < 0:
x = 0
print 'Negative
changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
 no case statement
a = ['cat', 'window',
'defenestrate']
for x in a:
print x, len(x)
 no arithmetic
progression, but
 range(10)  [0, 1, 2,
3, 4, 5, 6, 7, 8, 9]
 for i in
range(len(a)):
print i, a[i]
 do not modify the
sequence being iterated
over
Python in 90 minutes11
Loops: break, continue, else, o nothing
 break and continue
like C
 else after loop
exhaustion
for n in range(2,10):
for x in range(2,n):
if n % x == 0:
print n, 'equals',
x, '*', n/x
break
else:
# loop fell through
without finding a factor
print n, 'is prime'
 pass does nothing
 syntactic filler
while 1:
pass
Python in 90 minutes12
Exercise 3: for loop with if..else..
 ./hello2.py -m larry,cai,in,github
1. hello Larry
2. hello Cai
3. @
4. hello Github
Hints: think about loop in clean wayHints: think about loop in clean way
Python in 90 minutes13
Defining functions
def fib(n):
"""Print a Fibonacci
series up to n."""
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
>>> fib(2000)
 First line is docstring
 first look for variables in
local, then global
 need global to assign global
variables
def ask_ok(prompt,
retries=4, complaint='Yes
or no, please!'):
while 1:
ok = raw_input(prompt)
if ok in ('y', 'ye',
'yes'): return 1
if ok in ('n', 'no'):
return 0
retries = retries - 1
if retries < 0: raise
IOError, 'refusenik
error'
print complaint
>>> ask_ok('Really?')
Python in 90 minutes14
Modules
 import module:
import fibo
 Use modules via "name
space":
>>> fibo.fib(1000)
>>> fibo.__name__
'fibo'
 can give it a local name:
>>> fib = fibo.fib
>>> fib(500)
 function definition +
executable statements
 executed only when module
is imported
 modules have private symbol
tables
 avoids name clash for global
variables
 accessible as
module.globalname
 can import into name space:
>>> from fibo import fib,
fib2
>>> fib(500)
 can import all names defined
by module:
>>> from fibo import *
Python in 90 minutes15
Exercise 4: write into json config file
 JSON (JavaScript Object Notation) dump list of the
messages into external config files
 ./hello2.py -m larry,cai,in,github > config.json
 $ cat config.json
[
“larry”,
“cai”,
“in”,
“github”
]
Hints: json.dumps(data, indent=2)Hints: json.dumps(data, indent=2)
Python in 90 minutes16
Tuples and sequences
 lists, strings, tuples: examples
of sequence type
 tuple = values separated by
commas
>>> t = 123, 543, 'bar'
>>> t[0]
123
>>> t
(123, 543, 'bar')
 Tuples may be nested
>>> u = t, (1,2)
>>> u
((123, 542, 'bar'), (1,2))
 Empty tuples: ()
>>> empty = ()
>>> len(empty)
0
 sequence unpacking  distribute
elements across variables
>>> t = 123, 543, 'bar'
>>> x, y, z = t
>>> x
123
 packing always creates tuple
 unpacking works for any sequence
Python in 90 minutes17
Dictionaries
 like Tcl or awk associative
arrays
 indexed by keys
 keys are any immutable type:
e.g., tuples
 but not lists (mutable!)
 uses 'key: value' notation
>>> tel = {'hgs' : 7042, 'lennox':
7018}
>>> tel['cs'] = 7000
>>> tel
 no particular order
 delete elements with del
>>> del tel['foo']
 keys() method  unsorted list of
keys
>>> tel.keys()
['cs', 'lennox', 'hgs']
 use has_key() to check for existence
>>> tel.has_key('foo')
0
Python in 90 minutes18
Exercise 5: Generate report from internet
 Print MSFT, GOOG stock via Nasdaq live JSON with sort
 ./hello2.py –s MSFT,GOOG
“Getting live data from NASDAQ @ <current time>
GOOG: xx
MSFT: xx
$ curl -x <proxy> "http://finance.google.com/finance/info?client=ig&q=NASDAQ:MSFT,NASDAQ:GOOG “
fl = urlopen (“link”)
data = json.loads(contents)
[
{
"id": "694653"
,"t" : "GOOG"
,"e" : "NASDAQ"
,"l" : "701.96"
,"l_cur" : "701.96"
,"s": "0"
,"ltt":"4:00PM EST"
,"lt" : "Dec 14, 4:00PM EST"
,"c" : "-0.74"
,"cp" : "-0.10"
,"ccol" : "chr"
}
]
Hints: urlopen -> json.load -> data ..Hints: urlopen -> json.load -> data ..
Python in 90 minutes19
 Automate your daily work in python scripts
 Keep coding in python !!!
 Reading books and sample codes !!
Python in 90 minutes20
 Slides:
 http://www.slideshare.net/doughellmann/an-introduction-to-
the-zen-of-python - Doug Hellmann
 http://www.cs.columbia.edu/~hgs/teaching/ap/slides/python.ppt
 List books, articles, and electronic sources
 http://docs.python.org/2.7/
 Python cheatsheet: http://www.addedbytes.com/cheat-
sheets/python-cheat-sheet/
 Example for last exercise
 http://digitalpbk.com/stock/google-finance-get-stock-quote-realtime
Python in 90 minutes21

More Related Content

What's hot

Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rustnikomatsakis
 
Rust "Hot or Not" at Sioux
Rust "Hot or Not" at SiouxRust "Hot or Not" at Sioux
Rust "Hot or Not" at Siouxnikomatsakis
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Qiangning Hong
 
Ruby : Block, Proc and, lambda
Ruby : Block, Proc and, lambdaRuby : Block, Proc and, lambda
Ruby : Block, Proc and, lambdaMatthieuSegret
 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python Chetan Giridhar
 
Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureMike Fogus
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced pythonCharles-Axel Dein
 
What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)David Evans
 
Pharo - I have a dream @ Smalltalks Conference 2009
Pharo -  I have a dream @ Smalltalks Conference 2009Pharo -  I have a dream @ Smalltalks Conference 2009
Pharo - I have a dream @ Smalltalks Conference 2009Pharo
 
Working with NS2
Working with NS2Working with NS2
Working with NS2chanchal214
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.lnikolaeva
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingC4Media
 

What's hot (20)

Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
Python tour
Python tourPython tour
Python tour
 
uerj201212
uerj201212uerj201212
uerj201212
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Rust "Hot or Not" at Sioux
Rust "Hot or Not" at SiouxRust "Hot or Not" at Sioux
Rust "Hot or Not" at Sioux
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
Ruby : Block, Proc and, lambda
Ruby : Block, Proc and, lambdaRuby : Block, Proc and, lambda
Ruby : Block, Proc and, lambda
 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python
 
Ns2programs
Ns2programsNs2programs
Ns2programs
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of Clojure
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
 
What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)
 
Pharo - I have a dream @ Smalltalks Conference 2009
Pharo -  I have a dream @ Smalltalks Conference 2009Pharo -  I have a dream @ Smalltalks Conference 2009
Pharo - I have a dream @ Smalltalks Conference 2009
 
Working with NS2
Working with NS2Working with NS2
Working with NS2
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.
 
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
 
Python lec4
Python lec4Python lec4
Python lec4
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 

Similar to Python in 90mins

Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a PythonistRaji Engg
 
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
 
mooc_presentataion_mayankmanral on the subject puthon
mooc_presentataion_mayankmanral on the subject puthonmooc_presentataion_mayankmanral on the subject puthon
mooc_presentataion_mayankmanral on the subject puthongarvitbisht27
 
python within 50 page .ppt
python within 50 page .pptpython within 50 page .ppt
python within 50 page .pptsushil155005
 
python chapter 1
python chapter 1python chapter 1
python chapter 1Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 
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
 
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
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 

Similar to Python in 90mins (20)

Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a Pythonist
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
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
 
mooc_presentataion_mayankmanral on the subject puthon
mooc_presentataion_mayankmanral on the subject puthonmooc_presentataion_mayankmanral on the subject puthon
mooc_presentataion_mayankmanral on the subject puthon
 
python within 50 page .ppt
python within 50 page .pptpython within 50 page .ppt
python within 50 page .ppt
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
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
 
Python classes in mumbai
Python classes in mumbaiPython classes in mumbai
Python classes in mumbai
 
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 ...
 
PYTHON
PYTHONPYTHON
PYTHON
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python course
Python coursePython course
Python course
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
Python Tidbits
Python TidbitsPython Tidbits
Python Tidbits
 
Python for Dummies
Python for DummiesPython for Dummies
Python for Dummies
 
Python study material
Python study materialPython study material
Python study material
 

More from Larry Cai

Learn kubernetes in 90 minutes
Learn kubernetes in 90 minutesLearn kubernetes in 90 minutes
Learn kubernetes in 90 minutesLarry Cai
 
Learn jobDSL for Jenkins
Learn jobDSL for JenkinsLearn jobDSL for Jenkins
Learn jobDSL for JenkinsLarry Cai
 
Learn RabbitMQ with Python in 90mins
Learn RabbitMQ with Python in 90minsLearn RabbitMQ with Python in 90mins
Learn RabbitMQ with Python in 90minsLarry Cai
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90minsLarry Cai
 
Learn ELK in docker
Learn ELK in dockerLearn ELK in docker
Learn ELK in dockerLarry Cai
 
Software Engineer Talk
Software Engineer TalkSoftware Engineer Talk
Software Engineer TalkLarry Cai
 
Learn nginx in 90mins
Learn nginx in 90minsLearn nginx in 90mins
Learn nginx in 90minsLarry Cai
 
Learn basic ansible using docker
Learn basic ansible using dockerLearn basic ansible using docker
Learn basic ansible using dockerLarry Cai
 
Build service with_docker_in_90mins
Build service with_docker_in_90minsBuild service with_docker_in_90mins
Build service with_docker_in_90minsLarry Cai
 
Learn docker in 90 minutes
Learn docker in 90 minutesLearn docker in 90 minutes
Learn docker in 90 minutesLarry Cai
 
Learn Dashing Widget in 90 minutes
Learn Dashing Widget in 90 minutesLearn Dashing Widget in 90 minutes
Learn Dashing Widget in 90 minutesLarry Cai
 
Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with PythonLarry Cai
 
Jenkins Scriptler in 90mins
Jenkins Scriptler in 90minsJenkins Scriptler in 90mins
Jenkins Scriptler in 90minsLarry Cai
 
Python virtualenv & pip in 90 minutes
Python virtualenv & pip in 90 minutesPython virtualenv & pip in 90 minutes
Python virtualenv & pip in 90 minutesLarry Cai
 
Lead changes in software development
Lead changes in software developmentLead changes in software development
Lead changes in software developmentLarry Cai
 
Practical way to experience of Specification by Example
Practical way to experience of Specification by ExamplePractical way to experience of Specification by Example
Practical way to experience of Specification by ExampleLarry Cai
 
Experience from specification_by_examples
Experience from specification_by_examplesExperience from specification_by_examples
Experience from specification_by_examplesLarry Cai
 
Write book in markdown
Write book in markdownWrite book in markdown
Write book in markdownLarry Cai
 
Continuous Integration Introduction
Continuous Integration IntroductionContinuous Integration Introduction
Continuous Integration IntroductionLarry Cai
 
Agile & ALM tools
Agile & ALM toolsAgile & ALM tools
Agile & ALM toolsLarry Cai
 

More from Larry Cai (20)

Learn kubernetes in 90 minutes
Learn kubernetes in 90 minutesLearn kubernetes in 90 minutes
Learn kubernetes in 90 minutes
 
Learn jobDSL for Jenkins
Learn jobDSL for JenkinsLearn jobDSL for Jenkins
Learn jobDSL for Jenkins
 
Learn RabbitMQ with Python in 90mins
Learn RabbitMQ with Python in 90minsLearn RabbitMQ with Python in 90mins
Learn RabbitMQ with Python in 90mins
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
 
Learn ELK in docker
Learn ELK in dockerLearn ELK in docker
Learn ELK in docker
 
Software Engineer Talk
Software Engineer TalkSoftware Engineer Talk
Software Engineer Talk
 
Learn nginx in 90mins
Learn nginx in 90minsLearn nginx in 90mins
Learn nginx in 90mins
 
Learn basic ansible using docker
Learn basic ansible using dockerLearn basic ansible using docker
Learn basic ansible using docker
 
Build service with_docker_in_90mins
Build service with_docker_in_90minsBuild service with_docker_in_90mins
Build service with_docker_in_90mins
 
Learn docker in 90 minutes
Learn docker in 90 minutesLearn docker in 90 minutes
Learn docker in 90 minutes
 
Learn Dashing Widget in 90 minutes
Learn Dashing Widget in 90 minutesLearn Dashing Widget in 90 minutes
Learn Dashing Widget in 90 minutes
 
Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with Python
 
Jenkins Scriptler in 90mins
Jenkins Scriptler in 90minsJenkins Scriptler in 90mins
Jenkins Scriptler in 90mins
 
Python virtualenv & pip in 90 minutes
Python virtualenv & pip in 90 minutesPython virtualenv & pip in 90 minutes
Python virtualenv & pip in 90 minutes
 
Lead changes in software development
Lead changes in software developmentLead changes in software development
Lead changes in software development
 
Practical way to experience of Specification by Example
Practical way to experience of Specification by ExamplePractical way to experience of Specification by Example
Practical way to experience of Specification by Example
 
Experience from specification_by_examples
Experience from specification_by_examplesExperience from specification_by_examples
Experience from specification_by_examples
 
Write book in markdown
Write book in markdownWrite book in markdown
Write book in markdown
 
Continuous Integration Introduction
Continuous Integration IntroductionContinuous Integration Introduction
Continuous Integration Introduction
 
Agile & ALM tools
Agile & ALM toolsAgile & ALM tools
Agile & ALM tools
 

Python in 90mins

  • 2.  What is python ? Why Python ?  Exercise 1: Hello World  Exercise 2: String, List via command line  Exercise 3: For loop with if..else..  Exercise 4: Learn how to use module json to dump data  Exercise 5: Generate online NASDAQ data using json !!! Lots of materials are copied from http://www.cs.columbia.edu/~hgs/teaching/ap/slides/python.ppt and which is based on official tutorial by Guido van Rossum Exercises are created by Larry Cai Python in 90 minutes2
  • 3. What is Python ? And Why Python 2.7  Python is an easy to learn, powerful script programming language  Python is mature and better community compare to Perl  Python is high level over shell script  Python is well supported in OS as default compare to Ruby (which is also nice)  Python 3.x is quite new, not well accepted  Welcome to Python world Python in 90 minutes3
  • 4.  Python 2.7.x In Windows with Git Bash  http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi  Add into Path  How to run ?  /usr/local/bin/python  #!/usr/bin/env python  interactive use Python 2.7.3 (default,Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>  $ python script.py Python in 90 minutes4
  • 5.  Hello World  hello.py #!/usr/bin/env python for name in [“larry”,”cai”]: print "hello" , name Python in 90 minutes5
  • 6. Tips: Indent is important for python  Visible symbol in your favorite editor Python in 90 minutes6 Python forces to use a certainPython forces to use a certain indentation style instead of “{,}”indentation style instead of “{,}”
  • 7. Basic operations & program  Assignment:  size = 40  a = b = c = 3  Numbers  integer, float  complex numbers: 1j+3, abs(z)  Strings  'hello world', 'it's hot'  "bye world"  continuation via or use """ long text """" a,b = 0, 1 # non-zero = true while b < 10: # formatted output, without n print b, # multiple assignment a,b = b, a+b Python in 90 minutes7
  • 8. String & List operations  concatenate with + or neighbors  word = 'Help' + x  word = 'Help' 'a'  subscripting of strings  'Hello'[2]  'l'  slice: 'Hello'[1:2]  'el'  word[-1]  last character  len(word)  5  immutable: cannot assign to subscript  lists can be heterogeneous  a = ['spam', 'eggs', 100, 1234, 2*2]  Lists can be indexed and sliced:  a[0]  spam  a[:2]  ['spam', 'eggs']  Lists can be manipulated  a[2] = a[2] + 23  a[0:2] = [1,12]  a[0:0] = []  len(a)  5 Python in 90 minutes8
  • 9. Learn the standard script sample https://gist.github.com/4308811 Help doc Import library Function Main func Start here ! Python in 90 minutes9
  • 10. Exercise 2: remove characters  Practices basic operation in Interactive Shell  Add features to remove two characters each from input  ./hello2.py -m larry,cai hello rry hello i Hints: nameHints: names = messages.split(“,”)s = messages.split(“,”) Python in 90 minutes10
  • 11. Control flow: if & for x = int(raw_input("Please enter #:")) if x < 0: x = 0 print 'Negative changed to zero' elif x == 0: print 'Zero' elif x == 1: print 'Single' else: print 'More'  no case statement a = ['cat', 'window', 'defenestrate'] for x in a: print x, len(x)  no arithmetic progression, but  range(10)  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  for i in range(len(a)): print i, a[i]  do not modify the sequence being iterated over Python in 90 minutes11
  • 12. Loops: break, continue, else, o nothing  break and continue like C  else after loop exhaustion for n in range(2,10): for x in range(2,n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # loop fell through without finding a factor print n, 'is prime'  pass does nothing  syntactic filler while 1: pass Python in 90 minutes12
  • 13. Exercise 3: for loop with if..else..  ./hello2.py -m larry,cai,in,github 1. hello Larry 2. hello Cai 3. @ 4. hello Github Hints: think about loop in clean wayHints: think about loop in clean way Python in 90 minutes13
  • 14. Defining functions def fib(n): """Print a Fibonacci series up to n.""" a, b = 0, 1 while b < n: print b, a, b = b, a+b >>> fib(2000)  First line is docstring  first look for variables in local, then global  need global to assign global variables def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while 1: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return 1 if ok in ('n', 'no'): return 0 retries = retries - 1 if retries < 0: raise IOError, 'refusenik error' print complaint >>> ask_ok('Really?') Python in 90 minutes14
  • 15. Modules  import module: import fibo  Use modules via "name space": >>> fibo.fib(1000) >>> fibo.__name__ 'fibo'  can give it a local name: >>> fib = fibo.fib >>> fib(500)  function definition + executable statements  executed only when module is imported  modules have private symbol tables  avoids name clash for global variables  accessible as module.globalname  can import into name space: >>> from fibo import fib, fib2 >>> fib(500)  can import all names defined by module: >>> from fibo import * Python in 90 minutes15
  • 16. Exercise 4: write into json config file  JSON (JavaScript Object Notation) dump list of the messages into external config files  ./hello2.py -m larry,cai,in,github > config.json  $ cat config.json [ “larry”, “cai”, “in”, “github” ] Hints: json.dumps(data, indent=2)Hints: json.dumps(data, indent=2) Python in 90 minutes16
  • 17. Tuples and sequences  lists, strings, tuples: examples of sequence type  tuple = values separated by commas >>> t = 123, 543, 'bar' >>> t[0] 123 >>> t (123, 543, 'bar')  Tuples may be nested >>> u = t, (1,2) >>> u ((123, 542, 'bar'), (1,2))  Empty tuples: () >>> empty = () >>> len(empty) 0  sequence unpacking  distribute elements across variables >>> t = 123, 543, 'bar' >>> x, y, z = t >>> x 123  packing always creates tuple  unpacking works for any sequence Python in 90 minutes17
  • 18. Dictionaries  like Tcl or awk associative arrays  indexed by keys  keys are any immutable type: e.g., tuples  but not lists (mutable!)  uses 'key: value' notation >>> tel = {'hgs' : 7042, 'lennox': 7018} >>> tel['cs'] = 7000 >>> tel  no particular order  delete elements with del >>> del tel['foo']  keys() method  unsorted list of keys >>> tel.keys() ['cs', 'lennox', 'hgs']  use has_key() to check for existence >>> tel.has_key('foo') 0 Python in 90 minutes18
  • 19. Exercise 5: Generate report from internet  Print MSFT, GOOG stock via Nasdaq live JSON with sort  ./hello2.py –s MSFT,GOOG “Getting live data from NASDAQ @ <current time> GOOG: xx MSFT: xx $ curl -x <proxy> "http://finance.google.com/finance/info?client=ig&q=NASDAQ:MSFT,NASDAQ:GOOG “ fl = urlopen (“link”) data = json.loads(contents) [ { "id": "694653" ,"t" : "GOOG" ,"e" : "NASDAQ" ,"l" : "701.96" ,"l_cur" : "701.96" ,"s": "0" ,"ltt":"4:00PM EST" ,"lt" : "Dec 14, 4:00PM EST" ,"c" : "-0.74" ,"cp" : "-0.10" ,"ccol" : "chr" } ] Hints: urlopen -> json.load -> data ..Hints: urlopen -> json.load -> data .. Python in 90 minutes19
  • 20.  Automate your daily work in python scripts  Keep coding in python !!!  Reading books and sample codes !! Python in 90 minutes20
  • 21.  Slides:  http://www.slideshare.net/doughellmann/an-introduction-to- the-zen-of-python - Doug Hellmann  http://www.cs.columbia.edu/~hgs/teaching/ap/slides/python.ppt  List books, articles, and electronic sources  http://docs.python.org/2.7/  Python cheatsheet: http://www.addedbytes.com/cheat- sheets/python-cheat-sheet/  Example for last exercise  http://digitalpbk.com/stock/google-finance-get-stock-quote-realtime Python in 90 minutes21