SlideShare a Scribd company logo
1 of 71
Download to read offline
An	Introduction	to	the	Python	language	v0.1
and	demo	of	the	CMTS	Configuration	application
Download	the	IPython	Notebook
An	Introduction	to	the	Python	language	v0.1
and	demo	of	the	CMTS	Configuration	application
Download	the	IPython	Notebook
Running Python 2.7.10
2015/08/25
Shung-Hsi Yu
Email: First Name + Last Name (No hyphen, no spaces) at Gmail
Easy	to	Learn
In [1]: # Number
day = 25
price = 1.01
In [1]:
In [2]:
# Number
day = 25
price = 1.01
# String
s1 = 'this is a String'
s2 = "This works too"
In [1]:
In [2]:
In [3]:
# Number
day = 25
price = 1.01
# String
s1 = 'this is a String'
s2 = "This works too"
# List
fruits = ['apple', 'orange', 'banana']
In [1]:
In [2]:
In [3]:
In [4]:
# Number
day = 25
price = 1.01
# String
s1 = 'this is a String'
s2 = "This works too"
# List
fruits = ['apple', 'orange', 'banana']
# Dictionary
capital_of = {
'Taiwan': 'Taipei',
'United States': 'Washington D.C.',
'Brazil': 'Brasília',
'French': 'Paris'
}
Clear	Syntax
In [5]: fruits = ['apple', 'orange', 'banana']
# Access the first item
print fruits[0]
apple
In [6]: capital_of = {
'Taiwan': 'Taipei',
'United States': 'Washington D.C.',
'Brazil': 'Brasília',
'French': 'Paris'
}
# Access the value
print capital_of['Taiwan']
Taipei
In [6]:
In [7]:
capital_of = {
'Taiwan': 'Taipei',
'United States': 'Washington D.C.',
'Brazil': 'Brasília',
'French': 'Paris'
}
# Access the value
print capital_of['Taiwan']
Taipei
# Add the Capital City of Germany
capital_of['Germany'] = 'Berlin'
In [6]:
In [7]:
In [8]:
capital_of = {
'Taiwan': 'Taipei',
'United States': 'Washington D.C.',
'Brazil': 'Brasília',
'French': 'Paris'
}
# Access the value
print capital_of['Taiwan']
Taipei
# Add the Capital City of Germany
capital_of['Germany'] = 'Berlin'
print capital_of
{'United States': 'Washington D.C.', 'Brazil': 'Brasxc3xadlia', 'Taiwan': 'Taipe
i', 'Germany': 'Berlin', 'French': 'Paris'}
Variable	Unpacking
In [9]: capital_of = {
'Taiwan': 'Taipei',
'United States': 'Washington D.C.',
'Germany': 'Berlin',
'Brazil': 'Brasília',
'French': 'Paris'
}
In [9]:
In [10]:
capital_of = {
'Taiwan': 'Taipei',
'United States': 'Washington D.C.',
'Germany': 'Berlin',
'Brazil': 'Brasília',
'French': 'Paris'
}
for country_capital in capital_of.items():
print 'The capital city of', country_capital[0], 'is', country_capital[1]
The capital city of United States is Washington D.C.
The capital city of Brazil is Brasília
The capital city of Taiwan is Taipei
The capital city of Germany is Berlin
The capital city of French is Paris
In [9]:
In [10]:
In [11]:
capital_of = {
'Taiwan': 'Taipei',
'United States': 'Washington D.C.',
'Germany': 'Berlin',
'Brazil': 'Brasília',
'French': 'Paris'
}
for country_capital in capital_of.items():
print 'The capital city of', country_capital[0], 'is', country_capital[1]
The capital city of United States is Washington D.C.
The capital city of Brazil is Brasília
The capital city of Taiwan is Taipei
The capital city of Germany is Berlin
The capital city of French is Paris
for country, capital in capital_of.items():
print 'The capital city of', country, 'is', capital
The capital city of United States is Washington D.C.
The capital city of Brazil is Brasília
The capital city of Taiwan is Taipei
The capital city of Germany is Berlin
The capital city of French is Paris
In [12]: x, y = (1, 2)
print 'x =', x
print 'y =', y
x = 1
y = 2
In [12]:
In [13]:
x, y = (1, 2)
print 'x =', x
print 'y =', y
x = 1
y = 2
# Works with nested lists too
(first_name, last_name), position = [('Shung-Hsi', 'Yu'), 'intern']
print 'I am', first_name, last_name, ',', position
I am Shung-Hsi Yu , intern
Explicit
In [14]: colors = ['red', 'green', 'blue', 'yellow']
body_parts = ['nose', 'paw', 'teeth', 'neck']
animals = ['dog', 'cat', 'monkey', 'giraffe']
In [14]:
In [15]:
colors = ['red', 'green', 'blue', 'yellow']
body_parts = ['nose', 'paw', 'teeth', 'neck']
animals = ['dog', 'cat', 'monkey', 'giraffe']
for i in range(len(colors)):
print 'Got a', animals[i], body_parts[i], colors[i]
Got a dog nose red
Got a cat paw green
Got a monkey teeth blue
Got a giraffe neck yellow
In [14]:
In [15]:
In [16]:
colors = ['red', 'green', 'blue', 'yellow']
body_parts = ['nose', 'paw', 'teeth', 'neck']
animals = ['dog', 'cat', 'monkey', 'giraffe']
for i in range(len(colors)):
print 'Got a', animals[i], body_parts[i], colors[i]
Got a dog nose red
Got a cat paw green
Got a monkey teeth blue
Got a giraffe neck yellow
# Ask for colors, body_parts, animals explicitly and assign the values
for color, body_part, animal in zip(colors, body_parts, animals):
print 'Got a', color, body_part, animal
Got a red nose dog
Got a green paw cat
Got a blue teeth monkey
Got a yellow neck giraffe
In [17]: heights = [180, 157, 169, 172, 177]
min_height = 160
In [17]:
In [18]:
heights = [180, 157, 169, 172, 177]
min_height = 160
# If all the height in heights are greater than min_height
if all(height > min_height for height in heights):
print 'Everyone is over', min_height, 'cm!'
else:
print 'Someone is under', min_height, 'cm!'
Someone is under 160 cm!
In [17]:
In [18]:
In [19]:
heights = [180, 157, 169, 172, 177]
min_height = 160
# If all the height in heights are greater than min_height
if all(height > min_height for height in heights):
print 'Everyone is over', min_height, 'cm!'
else:
print 'Someone is under', min_height, 'cm!'
Someone is under 160 cm!
# If any of the height are greater than min_height
if any(height > min_height for height in heights):
print 'Someone is over', min_height, 'cm!'
else:
print 'Noboday is over', min_height, 'cm!'
Someone is over 160 cm!
In [20]: data = '657,663,669,675,681,687,693,699,705,711,717,723,729,735,741,747'
# Split the string at commas, and increment each by 6
print [int(freq) + 6 for freq in data.split(',')]
[663, 669, 675, 681, 687, 693, 699, 705, 711, 717, 723, 729, 735, 741, 747, 753]
In [21]: a = (1, 2)
b = (1, 2)
In [21]:
In [22]:
a = (1, 2)
b = (1, 2)
# Equal in value
print a == b
True
In [21]:
In [22]:
In [23]:
a = (1, 2)
b = (1, 2)
# Equal in value
print a == b
True
# The same object, where some language have ===
print a is b
False
In [24]: months = [
'January',
'February',
'March',
'April',
'May',
'June', # Exclude this
'July', # and this
'August',
'September',
'October',
'November',
'December'
]
excludes = ['June', 'July']
In [24]:
In [25]:
months = [
'January',
'February',
'March',
'April',
'May',
'June', # Exclude this
'July', # and this
'August',
'September',
'October',
'November',
'December'
]
excludes = ['June', 'July']
for month in months:
if month not in excludes:
print month
January
February
March
April
May
August
September
October
November
December
Reduce	Keystroke
In [26]: # Escaping manually
manual_escape = 'rn'
# Much simpler
regex_str = r'rn'
In [26]:
In [27]:
# Escaping manually
manual_escape = 'rn'
# Much simpler
regex_str = r'rn'
print regex_str == manual_escape
True
In [28]: # Manually breaking and appending 'n'
manual_long_str = 'This is the first linen' 
'Need to escape single quote ''
print manual_long_str
This is the first line
Need to escape single quote '
In [28]:
In [29]:
# Manually breaking and appending 'n'
manual_long_str = 'This is the first linen' 
'Need to escape single quote ''
print manual_long_str
This is the first line
Need to escape single quote '
# The n is taken literally
long_str = '''
This is the first line
Don't need to escape single quote '
'''
print long_str
This is the first line
Don't need to escape single quote '
In [30]: f = open('intro_to_python.txt', 'w')
f.write('''
This is
an
introduction to
Python
''')
# Bad things can happen when you forget this line
f.close()
In [30]:
In [31]:
f = open('intro_to_python.txt', 'w')
f.write('''
This is
an
introduction to
Python
''')
# Bad things can happen when you forget this line
f.close()
# f.close() is called automatically when leaving the idented block
# whether the code exit the block because of an exception or exiting normally
with open('intro_to_python.txt') as f:
print f.read()
This is
an
introduction to
Python
In [32]: # Print the content of the line along with the line number
with open('intro_to_python.txt') as f:
# enumerate(f) returns an index and the content of a single element in f each
time
for idx, line in enumerate(f):
print idx, line,
0 This is
1 an
2 introduction to
3 Python
In [33]: def fib(n):
"""Calculate the n-th integer in the Fibonacci Sequence
1, 1, 2, 3, 5, 8, 13, 21, ...
"""
# No curly brackets
if n < 1:
return 0
# elif instead of else if
elif 1 < n <= 2: # the equivalent of 1 < n and n <= 2
return 1
else:
return fib(n-1)+fib(n-2)
In [33]:
In [34]:
Out[34]:
def fib(n):
"""Calculate the n-th integer in the Fibonacci Sequence
1, 1, 2, 3, 5, 8, 13, 21, ...
"""
# No curly brackets
if n < 1:
return 0
# elif instead of else if
elif 1 < n <= 2: # the equivalent of 1 < n and n <= 2
return 1
else:
return fib(n-1)+fib(n-2)
fib(34)
3524578
Fast	to	Program
In [35]: from functools import wraps
store = {}
def memorize(func, storage=store):
# A function will be called instead of the original
@wraps(func)
def wrapper(arg):
"""This will only work when the target function takes a single parameter""
"
if arg not in storage:
print 'Running for', arg
# Call the original function and put it in cache
storage[arg] = func(arg)
else:
print 'Using cached value for', arg
return storage[arg]
# Replace the original function
return wrapper
In [36]: # I talked about @lru_cache in the presentation, but didn't realize that was new i
n Python 3.2
# So I'm keeping the memorize decorator I wrote
@memorize
def fib(n):
"""Calculate the n-th integer in the Fibonacci Sequence
1, 1, 2, 3, 5, 8, 13, 21, ...
"""
# No curly brackets
if n < 1:
return 0
# elif instead of else if
elif 1 < n <= 2: # the equivalent of 1 < n and n <= 2
return 1
else:
return fib(n-1)+fib(n-2)
In [36]:
In [37]:
# I talked about @lru_cache in the presentation, but didn't realize that was new i
n Python 3.2
# So I'm keeping the memorize decorator I wrote
@memorize
def fib(n):
"""Calculate the n-th integer in the Fibonacci Sequence
1, 1, 2, 3, 5, 8, 13, 21, ...
"""
# No curly brackets
if n < 1:
return 0
# elif instead of else if
elif 1 < n <= 2: # the equivalent of 1 < n and n <= 2
return 1
else:
return fib(n-1)+fib(n-2)
# Try calling it more than once
# The result will be cached
fib(34)
Running for 34
Running for 33
Running for 32
Running for 31
Running for 30
Running for 29
Running for 28
Running for 27
Running for 26
Running for 25
Running for 24
Running for 23
Running for 22
Running for 21
Batteries	Included
In [38]: # Both syntax return a set object
fruits = set(['orange', 'mango', 'apple', 'banana'])
companies = {'comcast', 'microsoft', 'apple', 'facebook', 'google'}
In [38]:
In [39]:
# Both syntax return a set object
fruits = set(['orange', 'mango', 'apple', 'banana'])
companies = {'comcast', 'microsoft', 'apple', 'facebook', 'google'}
# Find the common elements between the two
print companies & fruits
set(['apple'])
In [38]:
In [39]:
In [40]:
# Both syntax return a set object
fruits = set(['orange', 'mango', 'apple', 'banana'])
companies = {'comcast', 'microsoft', 'apple', 'facebook', 'google'}
# Find the common elements between the two
print companies & fruits
set(['apple'])
# Combine the two
print companies | fruits
set(['google', 'apple', 'banana', 'mango', 'facebook', 'comcast', 'orange', 'micro
soft'])
In [38]:
In [39]:
In [40]:
In [41]:
# Both syntax return a set object
fruits = set(['orange', 'mango', 'apple', 'banana'])
companies = {'comcast', 'microsoft', 'apple', 'facebook', 'google'}
# Find the common elements between the two
print companies & fruits
set(['apple'])
# Combine the two
print companies | fruits
set(['google', 'apple', 'banana', 'mango', 'facebook', 'comcast', 'orange', 'micro
soft'])
# Elements in one but not the other
print companies - fruits
set(['google', 'facebook', 'comcast', 'microsoft'])
In [ ]: import subprocess
# Run shell command `ls -ld`
p = subprocess.Popen(['ls', '-ld'], stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
print stdout
Large	Set	of	Libraries
Large	Set	of	Libraries
For	the	following	code	to	run,	please	install	the	Flask	library	using	command	line
prompt/shell	with	the	following	command:
pip install flask
In [43]: # Import will fail if Flask is not installed
from flask import Flask, request
In [44]: app = Flask('AppName')
# Direct HTTP GET Request for the root to this function
@app.route('/')
def index():
return '''
<h1>Hello World</h1>
'''
# Direct HTTP GET or POST Request for /receive_post to this function
@app.route('/receive_post', methods=['GET', 'POST'])
def receive_post():
# Checks the Request Method
if request.method == 'POST':
# Retrieve value from the form submitted
some_input = request.form['someinput']
return 'You typed ' + some_input
return '''
<form action="" method="post">
<input type=text name=someinput><br/>
<input type=submit>
</form>
'''
In [44]:
In [45]:
app = Flask('AppName')
# Direct HTTP GET Request for the root to this function
@app.route('/')
def index():
return '''
<h1>Hello World</h1>
'''
# Direct HTTP GET or POST Request for /receive_post to this function
@app.route('/receive_post', methods=['GET', 'POST'])
def receive_post():
# Checks the Request Method
if request.method == 'POST':
# Retrieve value from the form submitted
some_input = request.form['someinput']
return 'You typed ' + some_input
return '''
<form action="" method="post">
<input type=text name=someinput><br/>
<input type=submit>
</form>
'''
# A work-around that starts the web server in a different thread
# or else this notebook will continue to run the web server indefinitely
import threading
t = threading.Thread(target=app.run)
t.setDaemon(True)
t.start()
# DO NOT run this block more than once (without restarting the Ipython Kernel)
Now	navigate	to	 	and	you'll	see	'Hello	World'
Navigate	to	 	and	you'll	see	a	form	with	a	textbox	that
echos	your	input
http://localhost:5000/
http://localhost:5000/receive_post
More	Syntax	Sugar
Ternary	Operator
Ternary	Operator
In [46]: assign_one = True
will_be_one = 1 if assign_one else 2
print will_be_one
1
For-else	statement
For-else	statement
In [47]: fruits = ['apple', 'orange', 'banana', 'mango']
# To check if break have been called at all
# Need to have a boolean with a initial value
ate_all = True
for fruit in fruits:
if fruit == 'banana':
print 'I hate banana'
# And negate the boolean when going to call break
ate_all = False
break
print 'Eating', fruit
# Checks the value of the boolean
if ate_all:
print 'I ate all the fruits'
Eating apple
Eating orange
I hate banana
In [48]: # Try removing 'banana'
fruits = ['apple', 'orange', 'banana', 'mango']
for fruit in fruits:
if fruit == 'banana':
print 'I hate banana'
break
print 'Eating', fruit
else: # else == non-break
# This block runs when break is not called
# and every single element have been 'used' in the for-block
print 'I ate all the fruits'
Eating apple
Eating orange
I hate banana
Slicing
Slicing
In [49]: acronyms = ['CDCB', 'CMTS', 'CRAN', 'QUM']
Slicing
In [49]:
In [50]:
acronyms = ['CDCB', 'CMTS', 'CRAN', 'QUM']
# Correct the typo in the first element
acronyms[0] = 'CDCD'
print acronyms
['CDCD', 'CMTS', 'CRAN', 'QUM']
Slicing
In [49]:
In [50]:
In [51]:
acronyms = ['CDCB', 'CMTS', 'CRAN', 'QUM']
# Correct the typo in the first element
acronyms[0] = 'CDCD'
print acronyms
['CDCD', 'CMTS', 'CRAN', 'QUM']
# Insert another list at index 1
# And remove the original elements between index 1 (including) and index 2 (exclud
ing)
acronyms[1:2] = ['I-CMTS', 'M-CMTS']
print acronyms
['CDCD', 'I-CMTS', 'M-CMTS', 'CRAN', 'QUM']
Slicing
In [49]:
In [50]:
In [51]:
In [52]:
acronyms = ['CDCB', 'CMTS', 'CRAN', 'QUM']
# Correct the typo in the first element
acronyms[0] = 'CDCD'
print acronyms
['CDCD', 'CMTS', 'CRAN', 'QUM']
# Insert another list at index 1
# And remove the original elements between index 1 (including) and index 2 (exclud
ing)
acronyms[1:2] = ['I-CMTS', 'M-CMTS']
print acronyms
['CDCD', 'I-CMTS', 'M-CMTS', 'CRAN', 'QUM']
# Correcting the type in the last element
acronyms[-1] = 'QAM'
print acronyms
['CDCD', 'I-CMTS', 'M-CMTS', 'CRAN', 'QAM']
In [53]: # A string is also a sequence, just like list
# Take one from every three characters, starting from index 1
for char in 'You can iterate over a string'[1::3]:
print char
o
c
e
t
o
r
r
g
Try	it
Online	Python	Interpretor
Python	Official	Website
CMTS	Configuration	Tool	Demo
http://76.96.120.214/cmts/cmts_tools

More Related Content

What's hot

{shiny}と{leaflet}による地図アプリ開発Tips
{shiny}と{leaflet}による地図アプリ開発Tips{shiny}と{leaflet}による地図アプリ開発Tips
{shiny}と{leaflet}による地図アプリ開発TipsTakashi Kitano
 
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析Takashi Kitano
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School ProgrammersSiva Arunachalam
 
令和から本気出す
令和から本気出す令和から本気出す
令和から本気出すTakashi Kitano
 
Teeing Up Python - Code Golf
Teeing Up Python - Code GolfTeeing Up Python - Code Golf
Teeing Up Python - Code GolfYelp Engineering
 
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver){tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)Takashi Kitano
 
How fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practiceHow fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practiceTobias Pfeiffer
 
First step of Performance Tuning
First step of Performance TuningFirst step of Performance Tuning
First step of Performance Tuningrisou
 
Python avanzado - parte 1
Python avanzado - parte 1Python avanzado - parte 1
Python avanzado - parte 1coto
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 
Webmontag Berlin "coffee script"
Webmontag Berlin "coffee script"Webmontag Berlin "coffee script"
Webmontag Berlin "coffee script"Webmontag Berlin
 
python chapter 1
python chapter 1python chapter 1
python chapter 1Raghu nath
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]Haim Michael
 
The Error of Our Ways
The Error of Our WaysThe Error of Our Ways
The Error of Our WaysKevlin Henney
 
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of WranglingPLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of WranglingPlotly
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About RubyIan Bishop
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteDirkjan Bussink
 
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜Takashi Kitano
 

What's hot (20)

{shiny}と{leaflet}による地図アプリ開発Tips
{shiny}と{leaflet}による地図アプリ開発Tips{shiny}と{leaflet}による地図アプリ開発Tips
{shiny}と{leaflet}による地図アプリ開発Tips
 
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
令和から本気出す
令和から本気出す令和から本気出す
令和から本気出す
 
Teeing Up Python - Code Golf
Teeing Up Python - Code GolfTeeing Up Python - Code Golf
Teeing Up Python - Code Golf
 
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver){tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
 
Python 1
Python 1Python 1
Python 1
 
How fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practiceHow fast ist it really? Benchmarking in practice
How fast ist it really? Benchmarking in practice
 
First step of Performance Tuning
First step of Performance TuningFirst step of Performance Tuning
First step of Performance Tuning
 
Python avanzado - parte 1
Python avanzado - parte 1Python avanzado - parte 1
Python avanzado - parte 1
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
Webmontag Berlin "coffee script"
Webmontag Berlin "coffee script"Webmontag Berlin "coffee script"
Webmontag Berlin "coffee script"
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]
 
The Error of Our Ways
The Error of Our WaysThe Error of Our Ways
The Error of Our Ways
 
Codeware
CodewareCodeware
Codeware
 
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of WranglingPLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of Twente
 
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
 

Viewers also liked

Медицинское приложение для здоровых людей
Медицинское приложение для здоровых людейМедицинское приложение для здоровых людей
Медицинское приложение для здоровых людейDmitry Babaev
 
MEDCAN+B2B+Handbook+Single+Page+May17
MEDCAN+B2B+Handbook+Single+Page+May17MEDCAN+B2B+Handbook+Single+Page+May17
MEDCAN+B2B+Handbook+Single+Page+May17Jayla Pearce
 
Intergenerational Mortgage Exclusive to St James's Place
Intergenerational Mortgage Exclusive to St James's Place Intergenerational Mortgage Exclusive to St James's Place
Intergenerational Mortgage Exclusive to St James's Place Paresh Shah
 
Module 1 1.2-4 - atomic theory
Module 1   1.2-4 - atomic theoryModule 1   1.2-4 - atomic theory
Module 1 1.2-4 - atomic theoryaalford-iics
 
Shelly Shires Resume Jan 16
Shelly Shires Resume Jan 16Shelly Shires Resume Jan 16
Shelly Shires Resume Jan 16Shelly Shires
 
Digital Health Strategies: What Matters to Payers?
Digital Health Strategies: What Matters to Payers?Digital Health Strategies: What Matters to Payers?
Digital Health Strategies: What Matters to Payers?Susan Philip
 
Intergenerational Mortgages Exclusive to St James's Place
Intergenerational Mortgages Exclusive to St James's Place Intergenerational Mortgages Exclusive to St James's Place
Intergenerational Mortgages Exclusive to St James's Place Paresh Shah
 
Cosa è il counseling!? Voglio essere un counselor!
Cosa è il counseling!? Voglio essere un counselor!Cosa è il counseling!? Voglio essere un counselor!
Cosa è il counseling!? Voglio essere un counselor!Explicate
 
The Future of Meetings is Going Mobile
The Future of Meetings is Going Mobile The Future of Meetings is Going Mobile
The Future of Meetings is Going Mobile MeetingMogul
 
A CASE STUDY OF COENUROSIS IN GOAT VTH CHITWAN
A CASE STUDY OF COENUROSIS IN GOAT VTH CHITWANA CASE STUDY OF COENUROSIS IN GOAT VTH CHITWAN
A CASE STUDY OF COENUROSIS IN GOAT VTH CHITWANchetraj pathak
 
Digital Health Strategies: What Matters to Payers?
Digital Health Strategies: What Matters to Payers?Digital Health Strategies: What Matters to Payers?
Digital Health Strategies: What Matters to Payers?Susan Philip
 
Финансы для нефинансовых менеджеров
Финансы для нефинансовых менеджеровФинансы для нефинансовых менеджеров
Финансы для нефинансовых менеджеровDmitry Babaev
 
Medical app for healthy people
Medical app for healthy peopleMedical app for healthy people
Medical app for healthy peopleDmitry Babaev
 
Module 1 1.5a - isotopes
Module 1   1.5a - isotopesModule 1   1.5a - isotopes
Module 1 1.5a - isotopesaalford-iics
 
Венденговые аппарты "Вкусная помощь Экспресс"
Венденговые аппарты "Вкусная помощь Экспресс"Венденговые аппарты "Вкусная помощь Экспресс"
Венденговые аппарты "Вкусная помощь Экспресс"Вкусная помощь
 
Подарки на Новый год 2016 - Вкусная помощь
Подарки на Новый год 2016 - Вкусная помощьПодарки на Новый год 2016 - Вкусная помощь
Подарки на Новый год 2016 - Вкусная помощьВкусная помощь
 

Viewers also liked (16)

Медицинское приложение для здоровых людей
Медицинское приложение для здоровых людейМедицинское приложение для здоровых людей
Медицинское приложение для здоровых людей
 
MEDCAN+B2B+Handbook+Single+Page+May17
MEDCAN+B2B+Handbook+Single+Page+May17MEDCAN+B2B+Handbook+Single+Page+May17
MEDCAN+B2B+Handbook+Single+Page+May17
 
Intergenerational Mortgage Exclusive to St James's Place
Intergenerational Mortgage Exclusive to St James's Place Intergenerational Mortgage Exclusive to St James's Place
Intergenerational Mortgage Exclusive to St James's Place
 
Module 1 1.2-4 - atomic theory
Module 1   1.2-4 - atomic theoryModule 1   1.2-4 - atomic theory
Module 1 1.2-4 - atomic theory
 
Shelly Shires Resume Jan 16
Shelly Shires Resume Jan 16Shelly Shires Resume Jan 16
Shelly Shires Resume Jan 16
 
Digital Health Strategies: What Matters to Payers?
Digital Health Strategies: What Matters to Payers?Digital Health Strategies: What Matters to Payers?
Digital Health Strategies: What Matters to Payers?
 
Intergenerational Mortgages Exclusive to St James's Place
Intergenerational Mortgages Exclusive to St James's Place Intergenerational Mortgages Exclusive to St James's Place
Intergenerational Mortgages Exclusive to St James's Place
 
Cosa è il counseling!? Voglio essere un counselor!
Cosa è il counseling!? Voglio essere un counselor!Cosa è il counseling!? Voglio essere un counselor!
Cosa è il counseling!? Voglio essere un counselor!
 
The Future of Meetings is Going Mobile
The Future of Meetings is Going Mobile The Future of Meetings is Going Mobile
The Future of Meetings is Going Mobile
 
A CASE STUDY OF COENUROSIS IN GOAT VTH CHITWAN
A CASE STUDY OF COENUROSIS IN GOAT VTH CHITWANA CASE STUDY OF COENUROSIS IN GOAT VTH CHITWAN
A CASE STUDY OF COENUROSIS IN GOAT VTH CHITWAN
 
Digital Health Strategies: What Matters to Payers?
Digital Health Strategies: What Matters to Payers?Digital Health Strategies: What Matters to Payers?
Digital Health Strategies: What Matters to Payers?
 
Финансы для нефинансовых менеджеров
Финансы для нефинансовых менеджеровФинансы для нефинансовых менеджеров
Финансы для нефинансовых менеджеров
 
Medical app for healthy people
Medical app for healthy peopleMedical app for healthy people
Medical app for healthy people
 
Module 1 1.5a - isotopes
Module 1   1.5a - isotopesModule 1   1.5a - isotopes
Module 1 1.5a - isotopes
 
Венденговые аппарты "Вкусная помощь Экспресс"
Венденговые аппарты "Вкусная помощь Экспресс"Венденговые аппарты "Вкусная помощь Экспресс"
Венденговые аппарты "Вкусная помощь Экспресс"
 
Подарки на Новый год 2016 - Вкусная помощь
Подарки на Новый год 2016 - Вкусная помощьПодарки на Новый год 2016 - Вкусная помощь
Подарки на Новый год 2016 - Вкусная помощь
 

Similar to intro_to_python_20150825

第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎juzihua1102
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎anzhong70
 
python_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfpython_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfkeerthu0442
 
python file for easy way practicle programs
python file for easy way practicle programspython file for easy way practicle programs
python file for easy way practicle programsvineetdhand2004
 
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfsolution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfparthp5150s
 
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
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comShwetaAggarwal56
 
Creating a compiler in Perl 6
Creating a compiler in Perl 6Creating a compiler in Perl 6
Creating a compiler in Perl 6Andrew Shitov
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
python practicals-solution-2019-20-class-xii.pdf
python practicals-solution-2019-20-class-xii.pdfpython practicals-solution-2019-20-class-xii.pdf
python practicals-solution-2019-20-class-xii.pdfrajatxyz
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiMohamed Abdallah
 

Similar to intro_to_python_20150825 (20)

Python slide
Python slidePython slide
Python slide
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
ECE-PYTHON.docx
ECE-PYTHON.docxECE-PYTHON.docx
ECE-PYTHON.docx
 
python.pdf
python.pdfpython.pdf
python.pdf
 
python_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfpython_lab_manual_final (1).pdf
python_lab_manual_final (1).pdf
 
python file for easy way practicle programs
python file for easy way practicle programspython file for easy way practicle programs
python file for easy way practicle programs
 
Programs.doc
Programs.docPrograms.doc
Programs.doc
 
AI-Programs.pdf
AI-Programs.pdfAI-Programs.pdf
AI-Programs.pdf
 
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfsolution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
 
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
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.com
 
Creating a compiler in Perl 6
Creating a compiler in Perl 6Creating a compiler in Perl 6
Creating a compiler in Perl 6
 
xii cs practicals
xii cs practicalsxii cs practicals
xii cs practicals
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
python codes
python codespython codes
python codes
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
python practicals-solution-2019-20-class-xii.pdf
python practicals-solution-2019-20-class-xii.pdfpython practicals-solution-2019-20-class-xii.pdf
python practicals-solution-2019-20-class-xii.pdf
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry Pi
 

intro_to_python_20150825

  • 4. In [1]: # Number day = 25 price = 1.01
  • 5. In [1]: In [2]: # Number day = 25 price = 1.01 # String s1 = 'this is a String' s2 = "This works too"
  • 6. In [1]: In [2]: In [3]: # Number day = 25 price = 1.01 # String s1 = 'this is a String' s2 = "This works too" # List fruits = ['apple', 'orange', 'banana']
  • 7. In [1]: In [2]: In [3]: In [4]: # Number day = 25 price = 1.01 # String s1 = 'this is a String' s2 = "This works too" # List fruits = ['apple', 'orange', 'banana'] # Dictionary capital_of = { 'Taiwan': 'Taipei', 'United States': 'Washington D.C.', 'Brazil': 'Brasília', 'French': 'Paris' }
  • 9. In [5]: fruits = ['apple', 'orange', 'banana'] # Access the first item print fruits[0] apple
  • 10. In [6]: capital_of = { 'Taiwan': 'Taipei', 'United States': 'Washington D.C.', 'Brazil': 'Brasília', 'French': 'Paris' } # Access the value print capital_of['Taiwan'] Taipei
  • 11. In [6]: In [7]: capital_of = { 'Taiwan': 'Taipei', 'United States': 'Washington D.C.', 'Brazil': 'Brasília', 'French': 'Paris' } # Access the value print capital_of['Taiwan'] Taipei # Add the Capital City of Germany capital_of['Germany'] = 'Berlin'
  • 12. In [6]: In [7]: In [8]: capital_of = { 'Taiwan': 'Taipei', 'United States': 'Washington D.C.', 'Brazil': 'Brasília', 'French': 'Paris' } # Access the value print capital_of['Taiwan'] Taipei # Add the Capital City of Germany capital_of['Germany'] = 'Berlin' print capital_of {'United States': 'Washington D.C.', 'Brazil': 'Brasxc3xadlia', 'Taiwan': 'Taipe i', 'Germany': 'Berlin', 'French': 'Paris'}
  • 14. In [9]: capital_of = { 'Taiwan': 'Taipei', 'United States': 'Washington D.C.', 'Germany': 'Berlin', 'Brazil': 'Brasília', 'French': 'Paris' }
  • 15. In [9]: In [10]: capital_of = { 'Taiwan': 'Taipei', 'United States': 'Washington D.C.', 'Germany': 'Berlin', 'Brazil': 'Brasília', 'French': 'Paris' } for country_capital in capital_of.items(): print 'The capital city of', country_capital[0], 'is', country_capital[1] The capital city of United States is Washington D.C. The capital city of Brazil is Brasília The capital city of Taiwan is Taipei The capital city of Germany is Berlin The capital city of French is Paris
  • 16. In [9]: In [10]: In [11]: capital_of = { 'Taiwan': 'Taipei', 'United States': 'Washington D.C.', 'Germany': 'Berlin', 'Brazil': 'Brasília', 'French': 'Paris' } for country_capital in capital_of.items(): print 'The capital city of', country_capital[0], 'is', country_capital[1] The capital city of United States is Washington D.C. The capital city of Brazil is Brasília The capital city of Taiwan is Taipei The capital city of Germany is Berlin The capital city of French is Paris for country, capital in capital_of.items(): print 'The capital city of', country, 'is', capital The capital city of United States is Washington D.C. The capital city of Brazil is Brasília The capital city of Taiwan is Taipei The capital city of Germany is Berlin The capital city of French is Paris
  • 17. In [12]: x, y = (1, 2) print 'x =', x print 'y =', y x = 1 y = 2
  • 18. In [12]: In [13]: x, y = (1, 2) print 'x =', x print 'y =', y x = 1 y = 2 # Works with nested lists too (first_name, last_name), position = [('Shung-Hsi', 'Yu'), 'intern'] print 'I am', first_name, last_name, ',', position I am Shung-Hsi Yu , intern
  • 20. In [14]: colors = ['red', 'green', 'blue', 'yellow'] body_parts = ['nose', 'paw', 'teeth', 'neck'] animals = ['dog', 'cat', 'monkey', 'giraffe']
  • 21. In [14]: In [15]: colors = ['red', 'green', 'blue', 'yellow'] body_parts = ['nose', 'paw', 'teeth', 'neck'] animals = ['dog', 'cat', 'monkey', 'giraffe'] for i in range(len(colors)): print 'Got a', animals[i], body_parts[i], colors[i] Got a dog nose red Got a cat paw green Got a monkey teeth blue Got a giraffe neck yellow
  • 22. In [14]: In [15]: In [16]: colors = ['red', 'green', 'blue', 'yellow'] body_parts = ['nose', 'paw', 'teeth', 'neck'] animals = ['dog', 'cat', 'monkey', 'giraffe'] for i in range(len(colors)): print 'Got a', animals[i], body_parts[i], colors[i] Got a dog nose red Got a cat paw green Got a monkey teeth blue Got a giraffe neck yellow # Ask for colors, body_parts, animals explicitly and assign the values for color, body_part, animal in zip(colors, body_parts, animals): print 'Got a', color, body_part, animal Got a red nose dog Got a green paw cat Got a blue teeth monkey Got a yellow neck giraffe
  • 23. In [17]: heights = [180, 157, 169, 172, 177] min_height = 160
  • 24. In [17]: In [18]: heights = [180, 157, 169, 172, 177] min_height = 160 # If all the height in heights are greater than min_height if all(height > min_height for height in heights): print 'Everyone is over', min_height, 'cm!' else: print 'Someone is under', min_height, 'cm!' Someone is under 160 cm!
  • 25. In [17]: In [18]: In [19]: heights = [180, 157, 169, 172, 177] min_height = 160 # If all the height in heights are greater than min_height if all(height > min_height for height in heights): print 'Everyone is over', min_height, 'cm!' else: print 'Someone is under', min_height, 'cm!' Someone is under 160 cm! # If any of the height are greater than min_height if any(height > min_height for height in heights): print 'Someone is over', min_height, 'cm!' else: print 'Noboday is over', min_height, 'cm!' Someone is over 160 cm!
  • 26. In [20]: data = '657,663,669,675,681,687,693,699,705,711,717,723,729,735,741,747' # Split the string at commas, and increment each by 6 print [int(freq) + 6 for freq in data.split(',')] [663, 669, 675, 681, 687, 693, 699, 705, 711, 717, 723, 729, 735, 741, 747, 753]
  • 27. In [21]: a = (1, 2) b = (1, 2)
  • 28. In [21]: In [22]: a = (1, 2) b = (1, 2) # Equal in value print a == b True
  • 29. In [21]: In [22]: In [23]: a = (1, 2) b = (1, 2) # Equal in value print a == b True # The same object, where some language have === print a is b False
  • 30. In [24]: months = [ 'January', 'February', 'March', 'April', 'May', 'June', # Exclude this 'July', # and this 'August', 'September', 'October', 'November', 'December' ] excludes = ['June', 'July']
  • 31. In [24]: In [25]: months = [ 'January', 'February', 'March', 'April', 'May', 'June', # Exclude this 'July', # and this 'August', 'September', 'October', 'November', 'December' ] excludes = ['June', 'July'] for month in months: if month not in excludes: print month January February March April May August September October November December
  • 33. In [26]: # Escaping manually manual_escape = 'rn' # Much simpler regex_str = r'rn'
  • 34. In [26]: In [27]: # Escaping manually manual_escape = 'rn' # Much simpler regex_str = r'rn' print regex_str == manual_escape True
  • 35. In [28]: # Manually breaking and appending 'n' manual_long_str = 'This is the first linen' 'Need to escape single quote '' print manual_long_str This is the first line Need to escape single quote '
  • 36. In [28]: In [29]: # Manually breaking and appending 'n' manual_long_str = 'This is the first linen' 'Need to escape single quote '' print manual_long_str This is the first line Need to escape single quote ' # The n is taken literally long_str = ''' This is the first line Don't need to escape single quote ' ''' print long_str This is the first line Don't need to escape single quote '
  • 37. In [30]: f = open('intro_to_python.txt', 'w') f.write(''' This is an introduction to Python ''') # Bad things can happen when you forget this line f.close()
  • 38. In [30]: In [31]: f = open('intro_to_python.txt', 'w') f.write(''' This is an introduction to Python ''') # Bad things can happen when you forget this line f.close() # f.close() is called automatically when leaving the idented block # whether the code exit the block because of an exception or exiting normally with open('intro_to_python.txt') as f: print f.read() This is an introduction to Python
  • 39. In [32]: # Print the content of the line along with the line number with open('intro_to_python.txt') as f: # enumerate(f) returns an index and the content of a single element in f each time for idx, line in enumerate(f): print idx, line, 0 This is 1 an 2 introduction to 3 Python
  • 40. In [33]: def fib(n): """Calculate the n-th integer in the Fibonacci Sequence 1, 1, 2, 3, 5, 8, 13, 21, ... """ # No curly brackets if n < 1: return 0 # elif instead of else if elif 1 < n <= 2: # the equivalent of 1 < n and n <= 2 return 1 else: return fib(n-1)+fib(n-2)
  • 41. In [33]: In [34]: Out[34]: def fib(n): """Calculate the n-th integer in the Fibonacci Sequence 1, 1, 2, 3, 5, 8, 13, 21, ... """ # No curly brackets if n < 1: return 0 # elif instead of else if elif 1 < n <= 2: # the equivalent of 1 < n and n <= 2 return 1 else: return fib(n-1)+fib(n-2) fib(34) 3524578
  • 43. In [35]: from functools import wraps store = {} def memorize(func, storage=store): # A function will be called instead of the original @wraps(func) def wrapper(arg): """This will only work when the target function takes a single parameter"" " if arg not in storage: print 'Running for', arg # Call the original function and put it in cache storage[arg] = func(arg) else: print 'Using cached value for', arg return storage[arg] # Replace the original function return wrapper
  • 44. In [36]: # I talked about @lru_cache in the presentation, but didn't realize that was new i n Python 3.2 # So I'm keeping the memorize decorator I wrote @memorize def fib(n): """Calculate the n-th integer in the Fibonacci Sequence 1, 1, 2, 3, 5, 8, 13, 21, ... """ # No curly brackets if n < 1: return 0 # elif instead of else if elif 1 < n <= 2: # the equivalent of 1 < n and n <= 2 return 1 else: return fib(n-1)+fib(n-2)
  • 45. In [36]: In [37]: # I talked about @lru_cache in the presentation, but didn't realize that was new i n Python 3.2 # So I'm keeping the memorize decorator I wrote @memorize def fib(n): """Calculate the n-th integer in the Fibonacci Sequence 1, 1, 2, 3, 5, 8, 13, 21, ... """ # No curly brackets if n < 1: return 0 # elif instead of else if elif 1 < n <= 2: # the equivalent of 1 < n and n <= 2 return 1 else: return fib(n-1)+fib(n-2) # Try calling it more than once # The result will be cached fib(34) Running for 34 Running for 33 Running for 32 Running for 31 Running for 30 Running for 29 Running for 28 Running for 27 Running for 26 Running for 25 Running for 24 Running for 23 Running for 22 Running for 21
  • 47. In [38]: # Both syntax return a set object fruits = set(['orange', 'mango', 'apple', 'banana']) companies = {'comcast', 'microsoft', 'apple', 'facebook', 'google'}
  • 48. In [38]: In [39]: # Both syntax return a set object fruits = set(['orange', 'mango', 'apple', 'banana']) companies = {'comcast', 'microsoft', 'apple', 'facebook', 'google'} # Find the common elements between the two print companies & fruits set(['apple'])
  • 49. In [38]: In [39]: In [40]: # Both syntax return a set object fruits = set(['orange', 'mango', 'apple', 'banana']) companies = {'comcast', 'microsoft', 'apple', 'facebook', 'google'} # Find the common elements between the two print companies & fruits set(['apple']) # Combine the two print companies | fruits set(['google', 'apple', 'banana', 'mango', 'facebook', 'comcast', 'orange', 'micro soft'])
  • 50. In [38]: In [39]: In [40]: In [41]: # Both syntax return a set object fruits = set(['orange', 'mango', 'apple', 'banana']) companies = {'comcast', 'microsoft', 'apple', 'facebook', 'google'} # Find the common elements between the two print companies & fruits set(['apple']) # Combine the two print companies | fruits set(['google', 'apple', 'banana', 'mango', 'facebook', 'comcast', 'orange', 'micro soft']) # Elements in one but not the other print companies - fruits set(['google', 'facebook', 'comcast', 'microsoft'])
  • 51. In [ ]: import subprocess # Run shell command `ls -ld` p = subprocess.Popen(['ls', '-ld'], stdout=subprocess.PIPE) stdout, stderr = p.communicate() print stdout
  • 54. In [43]: # Import will fail if Flask is not installed from flask import Flask, request
  • 55. In [44]: app = Flask('AppName') # Direct HTTP GET Request for the root to this function @app.route('/') def index(): return ''' <h1>Hello World</h1> ''' # Direct HTTP GET or POST Request for /receive_post to this function @app.route('/receive_post', methods=['GET', 'POST']) def receive_post(): # Checks the Request Method if request.method == 'POST': # Retrieve value from the form submitted some_input = request.form['someinput'] return 'You typed ' + some_input return ''' <form action="" method="post"> <input type=text name=someinput><br/> <input type=submit> </form> '''
  • 56. In [44]: In [45]: app = Flask('AppName') # Direct HTTP GET Request for the root to this function @app.route('/') def index(): return ''' <h1>Hello World</h1> ''' # Direct HTTP GET or POST Request for /receive_post to this function @app.route('/receive_post', methods=['GET', 'POST']) def receive_post(): # Checks the Request Method if request.method == 'POST': # Retrieve value from the form submitted some_input = request.form['someinput'] return 'You typed ' + some_input return ''' <form action="" method="post"> <input type=text name=someinput><br/> <input type=submit> </form> ''' # A work-around that starts the web server in a different thread # or else this notebook will continue to run the web server indefinitely import threading t = threading.Thread(target=app.run) t.setDaemon(True) t.start() # DO NOT run this block more than once (without restarting the Ipython Kernel)
  • 60. Ternary Operator In [46]: assign_one = True will_be_one = 1 if assign_one else 2 print will_be_one 1
  • 62. For-else statement In [47]: fruits = ['apple', 'orange', 'banana', 'mango'] # To check if break have been called at all # Need to have a boolean with a initial value ate_all = True for fruit in fruits: if fruit == 'banana': print 'I hate banana' # And negate the boolean when going to call break ate_all = False break print 'Eating', fruit # Checks the value of the boolean if ate_all: print 'I ate all the fruits' Eating apple Eating orange I hate banana
  • 63. In [48]: # Try removing 'banana' fruits = ['apple', 'orange', 'banana', 'mango'] for fruit in fruits: if fruit == 'banana': print 'I hate banana' break print 'Eating', fruit else: # else == non-break # This block runs when break is not called # and every single element have been 'used' in the for-block print 'I ate all the fruits' Eating apple Eating orange I hate banana
  • 65. Slicing In [49]: acronyms = ['CDCB', 'CMTS', 'CRAN', 'QUM']
  • 66. Slicing In [49]: In [50]: acronyms = ['CDCB', 'CMTS', 'CRAN', 'QUM'] # Correct the typo in the first element acronyms[0] = 'CDCD' print acronyms ['CDCD', 'CMTS', 'CRAN', 'QUM']
  • 67. Slicing In [49]: In [50]: In [51]: acronyms = ['CDCB', 'CMTS', 'CRAN', 'QUM'] # Correct the typo in the first element acronyms[0] = 'CDCD' print acronyms ['CDCD', 'CMTS', 'CRAN', 'QUM'] # Insert another list at index 1 # And remove the original elements between index 1 (including) and index 2 (exclud ing) acronyms[1:2] = ['I-CMTS', 'M-CMTS'] print acronyms ['CDCD', 'I-CMTS', 'M-CMTS', 'CRAN', 'QUM']
  • 68. Slicing In [49]: In [50]: In [51]: In [52]: acronyms = ['CDCB', 'CMTS', 'CRAN', 'QUM'] # Correct the typo in the first element acronyms[0] = 'CDCD' print acronyms ['CDCD', 'CMTS', 'CRAN', 'QUM'] # Insert another list at index 1 # And remove the original elements between index 1 (including) and index 2 (exclud ing) acronyms[1:2] = ['I-CMTS', 'M-CMTS'] print acronyms ['CDCD', 'I-CMTS', 'M-CMTS', 'CRAN', 'QUM'] # Correcting the type in the last element acronyms[-1] = 'QAM' print acronyms ['CDCD', 'I-CMTS', 'M-CMTS', 'CRAN', 'QAM']
  • 69. In [53]: # A string is also a sequence, just like list # Take one from every three characters, starting from index 1 for char in 'You can iterate over a string'[1::3]: print char o c e t o r r g