This document provides an introduction to the Python programming language and demonstrates its syntax and features through examples in an IPython notebook. It shows how to define variables of different data types like numbers, strings, lists and dictionaries. It also demonstrates Python's clear, explicit syntax for accessing elements, unpacking variables, iterating over collections, and using conditional statements and functions. The document highlights how Python comes with many built-in tools like sets, regular expressions and file I/O, and how functions can be decorated for caching results. Overall, it presents Python as an easy to learn, explicit yet concise language with a large standard library.
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'}
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
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
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]
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)
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
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