Learn to Program with Python
Chia James Chang
[email protected] Microsoft Corp.
Volunteer teaching @ROLF, ROLCA, CoderDojo Silicon Valley
Agenda
• Introduction
• 1. First Steps
• 2. Basics
• 3. Operators and Expressions
• 4. Control Flow
• 5. Drawing with Turtle
• 6. Functions and Modules
9/12/2015 Learn to Program with Python 2
Agenda
• 7. Data Structures
• 8. Input Output
• 9. Object Oriented Programming
• 10. Exceptions
• 11. Standard Library
• 12. More
• What Next
9/12/2015 Learn to Program with Python 3
Resources
• Python.org Home (download, document, community,
etc.) for Python 3.
• A Byte of Python v1.9.2 (for Python 3.0), Swaroop C H.
– A Byte of Python website (for Python 2.0)
• Invent Your Own Computer Games with Python 3rd
Edition, Al Sweigart, March, 2015.
• Introduction to Python, Steve Dower, Microsoft, 2015.
• “Learn to Program with Python” website:
– http://techsamaritan.org/courses/jameschang/python/Lea
rnToProgramWithPython.html
9/12/2015 Learn to Program with Python 4
Resources (cont.)
• Learning Python 5th Ed., Mark Lutz, O’Reilly,
2013.
• IDE (Integrated development environment)
– Python’s IDLE (part of Python 3 installation)
– PyCharm Community Edition (recommended)
– Visual Studio Community Edition (optional)
• Python 2 vs Python 3
– What’s New In Python 3.0
9/12/2015 Learn to Program with Python 5
Class Schedule
9/12/2015 Learn to Program with Python 6
Weekly Schedule
• First Week on 8/9/2015
• Second Week on 8/16/2015
• Third Week on 8/23/2015
• Fourth Week on 8/30/2015
• Fifth Week on 9/6/2015
• Sixth Week on 9/13/2015
9/12/2015 Learn to Program with Python 7
First week on 8/9/2015
• Python was up and running on both PCs and Macs.
• PyCharm was up and running on both PCs and Macs.
• Learned how to use the tools, PyCharm and Python
console.
• Wrote the first program, "Hello, World!", ran it, and
extended it.
• Finished the Introduction, 1. First Step, and touched
the 2. Basics.
• Wrote some more tiny programs to get our hands wet.
• etc.
9/12/2015 Learn to Program with Python 8
Second Week on 8/16/2015
• 2. Basics.
• 3. Operators and Expressions
• 4. Control Flow
• Write lots of small programs
9/12/2015 Learn to Program with Python 9
Third week on 8/23/2015
• 5. Drawing with Turtle
• 6. Functions and Modules
• 7. Data Structures
• 8. Input Output
• Write lots of small programs
9/12/2015 Learn to Program with Python 10
Fourth week on 8/30/2015
• 9. Object Oriented Programming
• 10. Exceptions
• 11. Standard Library
• 12. More
• Write lots of small programs
9/12/2015 Learn to Program with Python 11
Fifth week on 9/6/2015
• Review all the subjects covered in the class.
• Work as a team.
• Design and develop one or more projects
selected from instructor’s list.
9/12/2015 Learn to Program with Python 12
Six week on 9/13/2015
• Work as a team.
• Design and develop one or more projects at
students’ own choices.
9/12/2015 Learn to Program with Python 13
Introduction
9/12/2015 Learn to Program with Python 14
Why Learn Computer Programming?
• Programming fosters creativity, reasoning, and
problem solving.
• Programming is fun and challenging.
• “As young people create Scratch projects, they are
not just learning how to write computer
programs. They are learning to think creatively,
reason systematically, and work collaboratively—
essential skills for success and happiness in
today’s world.” --- Professor Mitchel Resnick,
Director, MIT Scratch Team, MIT Media Lab.
9/12/2015 Learn to Program with Python 15
Think Like a Computer Scientist
• This way of thinking combines some of the best
features of:
– Mathematicians:
• use formal languages to denote ideas (specifically
computations).
– Engineers:
• design things, assemble components into systems and
evaluate tradeoffs among alternatives.
– Computer Scientists:
• observe the behavior of complex systems, from hypotheses,
and test predictions.
• Source: Think Python: How to Think Like a Computer Scientist, Allen Downey, Version 2.0.6,
February 2013, Green Tea Press, Needham, Massachusetts.
Think Like a Computer Scientist
• The single most important skill for a computer
scientist is problem solving.
– Problem-solving means the ability to formulate
problems, think creatively about solutions, and
express a solution clearly and accurately.
– The process of learning to program is an excellent
opportunity to practice problem-solving skills.
What is programming?
• Programming means to write programs, code,
or instructions that cause a computer to
perform some kind of action.
9/12/2015 Learn to Program with Python 18
What is a program?
• A program is a sequence of instruction or code
that specifies how to perform a computation.
– input: Get data from the keyboard, a file, or some
other device.
– output: Display data on the screen or send data to a
file or other device.
– magic: magic code to perform a computation
• Programming is the process of breaking a large, complex
task into smaller and smaller subtasks until the subtasks
are simple enough to be performed with one of these
basic instructions.
What is debugging?
• Programming is error-prone. For unusual reasons,
programming errors are called bugs and the process
of tracking them down is called debugging.
• Three kinds of errors can occur in a program:
– Syntax errors: syntax refers to the structure of a program
and the rules about that structure. For example,
parentheses have to come in matching pairs, so (1 + 2) is
legal, but 8) is a syntax error.
– Runtime errors: the error does not appear until after the
program has started running.
– Semantic errors: If there is a semantic (meaning or logic)
error in your program, it will run successfully without any
error but it will no do the right thing.
What is debugging?
• Three kinds of errors can occur in a program:
– Syntax errors: syntax refers to the structure of a
program and the rules about that structure. For
example, parentheses have to come in matching
pairs, so (1 + 2) is legal, but 8) is a syntax error.
– Runtime errors: the error does not appear until
after the program has started running.
– Semantic errors: If there is a semantic (meaning or
logic) error in your program, it will run successfully
without any error but it will no do the right thing.
Why Python?
Simple Interpreted
Easy to Learn Object Oriented
Free and Open Source Extensible
High-Level Language Embeddable
Portable Extensive Libraries
9/12/2015 Learn to Program with Python 22
History of Python
• Python’s name was came from Monty Python’s Flying
Circus of British comedy show first broadcast in the
1970s.
• Python was created in 1989 by Guido van
Rossum in the Netherlands.
• 2005-2012: Google
• 2013: Dropbox
• Python 2 released on 2000
• Python 3 released on 2008
9/12/2015 Learn to Program with Python 23
How to Learn to Code?
• Like anything you try for the first time, it’s always
best to start with the basics.
• Try each of the examples and the programming
exercises, so you can see how they work.
• The better you understand the basics, the easier
it will be to understand more complicated ideas
later on.
• Break a problem down into smaller pieces.
• If that still doesn’t help, sometimes it’s best to
just leave it alone for a while. Sleep on it, and
come back to it another day.
9/12/2015 Learn to Program with Python 24
Have Fun!
• Think of programming as a way to create some
fun games or applications that you can share
with your friends or others.
• Learning to program is a wonderful mental
exercise and the results can be very
rewarding.
• Most of all, whatever you do, have fun!
9/12/2015 Learn to Program with Python 25
1. First Steps
9/12/2015 Learn to Program with Python 26
First Steps
• Start python.exe at the command line OR
• Using Python Interactive Shell
– Start -> Programs -> Python 3.4 -> IDLE (Python GUI).
– Enter Python statements and press ENTER to run.
print(‘Hello, World!’)
Congratulations! You’ve just created your first Python
program!
• Getting Help
– help(print)
9/12/2015 Learn to Program with Python 27
Using a Program Source File
• Creating a Program Source File via Python IDLE
– File -> New Window then File -> Save
– Create a new directory: C:\python\exercises
– File name: hello_world.py
#Filename: hello_world.py
print(‘Hello, World!’)
• Running the program
– Using IDLE
• Run -> Run Module or keyboard shortcut F5.
– Command line
• > python HelloWorld.py
9/12/2015 Learn to Program with Python 28
For Windows Users
• Open Terminal
– Start -> Run -> type “cmd”
– python -V
• Open IDLE
– Start -> Programs -> Python 3.4 -> IDLE (Python
GUI)
• Open PyCharm
– Start -> Run -> type “pycharm”
9/12/2015 Learn to Program with Python 29
For Mac OS X Users
• Open Terminal
– Open the terminal by pressing Command+Space
keys (to open Spotlight search), type Terminal and
press enter.
– python –V
• Open IDE
9/12/2015 Learn to Program with Python 30
Getting Familiar with PyCharm
• Change Settting: File->Settings
– Show line numbers: Editor->General->Appearance
– Tab->Spaces: Editor->Code Style->Default Indent
Options
• Create Project: File->New Project…
– Location: C:\PythonWork
– Interpreter: C:\Python34
9/12/2015 Learn to Program with Python 31
2. Basics
9/12/2015 Learn to Program with Python 32
Basics Data Types
• Numbers
– integers: 2
– floating point (float): 3.23
– complex numbers: (-5+4j)
– Literal Constants: use its value literally, it’s
constant
• number: 5, 1.23, 9.25e-3
• String: ‘Hello World!’
• User defined types using classes and objects
9/12/2015 Learn to Program with Python 33
Numbers and Math
• Numbers in Python are of three types - integers,
floating point and complex numbers.
spam = 10
fp = 10.50
• Math
2 + 2
import math
degrees = 45
radians = degrees / 360.0 * 2 * math.pi
9/12/2015 Learn to Program with Python 34
Comments
• Comment, # symbol: anything to the right of
the # symbol is a comment.
# Computer programming is fun!
# Python programming is very fun!
# print(2+2)
9/12/2015 Learn to Program with Python 35
Variables and Types
• Variables stores some information and their value
can vary.
• Variables and Values
fizz = 10
eggs = 15
print(fizz)
spam = fizz + eggs
print(spam)
25
• Values Have Types
– use the type() function to find out the type
type(spam)
<class 'int'>
9/12/2015 Learn to Program with Python 36
Naming Variables
• The first character of the identifier must be a
letter of the alphabet or an underscore (‘_’).
• The rest of the identifier name can consist of
letters, underscores (‘_’) or digits (0-9).
• Identifier names are case-sensitive. myname
and myName are not the same.
• Valid identifiers: i, name_23, _my_name
9/12/2015 Learn to Program with Python 37
Variables and Values
• Python has strong, dynamic typing
• Values never change type unless you make
them
– This is the “strong” part
• Variables change type whenever you assign to
them
– This is the “dynamic” part
9/12/2015 Learn to Program with Python 38
What Type is ‘a’?
"100"
"100"
9/12/2015 Learn to Program with Python 39
What Type is ‘x’?
from import
if
else
9/12/2015 Learn to Program with Python 40
What Type is ‘c’?
"100"
9/12/2015 Learn to Program with Python 41
What Type is ‘c’?
"100"
9/12/2015 Learn to Program with Python 42
Some Other Surprises…
"abc"
9/12/2015 Learn to Program with Python 43
Strings
• A string is a sequence of characters enclosed either
single or double quote marks. Strings are Immutable.
• Single Quotes
msg = 'Quote me on this'
• Double Quotes work exactly as single quotes
msg = "What’s your name?"
• Triple Quotes (""" or ''')
msg = '''This is the first line.
This is the second line.
'''
9/12/2015 Learn to Program with Python 44
Escape Sequences
'What\'s your name?'
"Newlines are indicated by \n"
• Raw Strings
r"Newlines are indicated by \n"
R"Newlines are indicated by \n"
9/12/2015 Learn to Program with Python 45
Strings Concatenation
• Concatenate Strings
'Hello, ' + 'World!'
• Two string literals side by side, they are
automatically concatenated by Python
'What\'s ' 'your name?'
• Multiplying Strings
print(10 * 'a')
9/12/2015 Learn to Program with Python 46
Strings Format
• The format Method: construct strings from
other information
age = 25
name = 'John'
print(name + " is " + age + " years old.")
print(name + " is " + str(age) + " years old.")
print("%s is %d years old." % (name, age))
print("{0} is {1} years old.".format(name, age))
9/12/2015 Learn to Program with Python 47
Keeping Text in Strings
• Keeping Text in Strings (0-based index)
"abcde"[0]
"abcde"[1]
"abcde"[10]
"abcde"[1:3]
"abcde"[:3]
"abcde"[3:]
len("abcde")
"abc" + "def"
9/12/2015 Learn to Program with Python 48
Indentation!!!
• Indentation: leading whitespace (spaces or tabs) at the
beginning of the statement.
– to determine the grouping of statements.
• Statements which go together must have the same
indentation. Each such set of statements is called a
block.
• Do not use a mixture of tabs and spaces for the
indentation.
• Use four spaces or one tab for each indentation level.
while True:
print(‘Hello, World!’)
9/12/2015 Learn to Program with Python 49
More About Strings
• Strings are also objects and have methods.
name = 'Python'
if name.startswith('Py'):
print('Yes, the string starts with “Py"')
if 't' in name:
print('Yes, it contains the string "t"')
if name.find('thon') != -1:
print('Yes, it contains the string "thon"')
9/12/2015 Learn to Program with Python 50
3. Operators and
Expressions
9/12/2015 Learn to Program with Python 51
Operators and Expressions
• Expression can be broken down into operators
and operands.
• Operators:
– Numerical: +, -, *, /,**, //, %
– Bitwise: <<, >>, &, |, ^, ~
– Comparison: <, >, <=, >=, ==, !=
– Boolean: not, and, or
9/12/2015 Learn to Program with Python 52
What Will You Get?
3 + 5
- 5.2
2 * 3
3 ** 4
4 / 3
4 // 3
8 % 3
9/12/2015 Learn to Program with Python 53
What Will You Get?
2 << 2
11 >> 1
5 & 3
5 | 3
5 ^ 3
~5 # -6
5 < 3
3 < 5
5 > 3
9/12/2015 Learn to Program with Python 54
What Will You Get?
2 + 3 * 4 – 6 / 2
9/12/2015 Learn to Program with Python 55
Order of operations
• Order of operations (PEMDAS)
– Parentheses: 2 * (3 – 1)
– Exponentiation: 3*1**3
– Multiplication and Division: 2 * 3 -1; 6 + 4 / 2
– Addition and Subtraction: 2 + 2 - 1
• Operators with the same precedence are
evaluated from left to right (except
exponentiation).
• Changing the Order of Evaluation: use
parentheses
(2 + 3) * 4
9/12/2015 Learn to Program with Python 56
What Will You Get?
2 + 3 * 4 – 6 / 2
(2 + 3) * 4 – 6 / 2
2 + (3 * 4) – (6 / 2)
2 + 3 * (4 – 6) / 2
9/12/2015 Learn to Program with Python 57
Temperature Converter
• Convert Celsius to Fahrenheit
– fahrenheit = (celsius * 9 / 5) + 32
• Convert Fahrenheit
– celsius = (fahrenheit - 32) * 5 / 9
• Temperature Converter
– Enter celsius
• output celsius, fahrenheit
• output fahrenheit, celsius
9/12/2015 Learn to Program with Python 58
4. Control Flow
9/12/2015 Learn to Program with Python 59
Booleans
• Boolean: True or False
1 == 1
1 == 2
• Converting Between Data Types
– int(), float(), str()
print(int(3.9))
print(float("Three point two"))
9/12/2015 Learn to Program with Python 60
Conditions
• Conditions Help Us Compare Things
Symbol Definition
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
9/12/2015 Learn to Program with Python 61
The if Statement
color = 'white' Start
if color == 'red':
color = 'orange' Is the
Yes Set the
color
elif color == 'orange': color orange
red?
color = 'yellow'
No
else:
color = 'red' Is the Yes Set the
color
color yellow
orange?
No
Set the color red
9/12/2015 Learn to Program with Python 62
The while Statement
running = True
while running:
print(“Python is fun!”)
step = 0
while step < 10:
print("%s: Python is awesome!" % step)
step += 1
9/12/2015 Learn to Program with Python 63
The break Statement
• Breaking out of a loop statement
while True:
s = (input('Enter something: '))
if s == 'quit':
break
print('Length of the string is ', len(s))
9/12/2015 Learn to Program with Python 64
The continue Statement
• Skip the rest of statements in the current loop
block and continue to the next iteration of the
loop.
while True:
s = (input('Enter something: '))
if s == 'quit':
break
if len(s) < 3:
print('Too short: ', len(s))
continue
print('Input is too long: ', len(s))
9/12/2015 Learn to Program with Python 65
For Loop
• Print multiple times
print('hello')
print('hello')
print('hello')
print('hello')
print('hello')
9/12/2015 Learn to Program with Python 66
For Loop
• Using for Loops
for x in range(0, 5):
print('hello')
9/12/2015 Learn to Program with Python 67
Temperature Converter
• Generic Temperature Converter
– Enter “c2f” & celsius, output fahrenheit
– Enter “f2c” & fahrenheit, output celsius
9/12/2015 Learn to Program with Python 68
5. Drawing with Turtles
9/12/2015 Learn to Program with Python 69
Drawing with Turtles
• A turtle in Python is sort of like a turtle in the real
world.
• In the world of Python, a turtle is a small, black
arrow that moves slowly around the screen.
• The turtle is a nice way to learn some of the
basics of computer graphics.
• Python has a special module called turtle that we
can use to learn how computers draw pictures on
a screen.
9/12/2015 Learn to Program with Python 70
Using Python’s turtle Module
• A module in Python is a way of providing
useful code to be used by another program.
• Turtle can draw intricate shapes using
programs that repeat simple moves.
• Turtle graphics for Tk
– https://docs.python.org/3/library/turtle.html
• tkinter package
import turtle
9/12/2015 Learn to Program with Python 71
Using Python’s turtle Module
• Pixel is a tiny, square dot on the computer monitor.
• t.forward(50) # advance 50 pixels (or backward)
• t.left(90) # turn left 90 degrees (or right)
• t.reset() # clears the canvas and put the turtle back at
the starting position
• t.clear() # clears the screen and leaves the turtle where
it is
• t.up() # pick up the pen and stop drawing
• t.down() # put the pen back down and start drawing
again
9/12/2015 Learn to Program with Python 72
Turtle Program
1. Show the Turtle
2. Can you draw a petal?
3. Can you draw a circle?
4. Can you draw 4 circles?
5. Can you draw all 24 petals?
9/12/2015 Learn to Program with Python 73
1. Show a Turtle
import turtle
window = turtle.Screen()
t = turtle.Turtle()
window.exitonclick()
9/12/2015 Learn to Program with Python 74
2. Can you draw a petal?
#draw a petal
import turtle
window = turtle.Screen()
t = turtle.Turtle()
t.left(15)
t.forward(50)
t.left(157)
t.forward(50)
window.exitonclick()
9/12/2015 Learn to Program with Python 75
3. Can you draw a circle?
import turtle
window = turtle.Screen()
t = turtle.Turtle()
t.left(90)
t.forward(100)
t.right(90)
t.circle(10)
window.exitonclick()
9/12/2015 Learn to Program with Python 76
4. Can You draw 4 circles?
# Hint: for x in range(0, 3):
import turtle
window = turtle.Screen()
t = turtle.Turtle()
t.left(90)
t.forward(100)
t.right(90)
t.circle(10)
window.exitonclick()
9/12/2015 Learn to Program with Python 77
4. Can You draw 4 circles?
import turtle
window = turtle.Screen()
t = turtle.Turtle()
for x in range(0, 4):
t.left(90)
t.forward(100)
t.right(90)
t.circle(10)
t.right(90)
window.exitonclick()
9/12/2015 Learn to Program with Python 78
5. Can you draw all 24 petals?
#draw all petals
import turtle
window = turtle.Screen()
t = turtle.Turtle()
for i in range(1,24):
t.left(15)
t.forward(50)
t.left(157)
t.forward(50)
window.exitonclick()
9/12/2015 Learn to Program with Python 79
6. Functions and Modules
9/12/2015 Learn to Program with Python 80
Functions
• Functions are reusable pieces of programs.
– ex_function.py
• Function Parameters
– ex_func_param.py
def functionName(params):
block of statements
def printMax(a, b):
if a > b:
print(a, ' is maximum')
elif a == b:
print(a, ' is equal to', b)
else:
print(b, ' is maximum')
printMax(3, 4)
9/12/2015 Learn to Program with Python 81
Local Variables
• Scope of the variable
– ex_func_local.py
x = 50
def func(x):
print('x is ', x)
x = 2
print('Changed local x to ', x)
func(x)
print('Value of x is ', x)
9/12/2015 Learn to Program with Python 82
global Variables
• global statement
– ex_func_global.py
x = 50
def func():
global x
print('x is ', x)
x = 2
print('Changed local x to ', x)
func(x)
print('Value of x is ', x)
9/12/2015 Learn to Program with Python 83
nonlocal Variables
• nonlocal scopes are observed when you define
functions inside functions.
– ex_func_nonlocal.py
def func_outer():
x = 2
print('x is ', x)
def func_inner():
nonlocal x
x = 5
func_inner()
print('Changed local x to ', x)
func_outer()
9/12/2015 Learn to Program with Python 84
Default Argument Values
• Parameter name with assignment operator (=)
followed by the default value.
def say(message, times = 1):
print(message * times)
#
say('Hello')
say('World', 5)
9/12/2015 Learn to Program with Python 85
Keyword Arguments
def func(a, b=5, c=10):
print('a is ', a, ' and b is ', b, ' and c is ', c)
#
func(1,2,3)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
9/12/2015 Learn to Program with Python 86
The return Statement
• return from a function, can optionally return a
value.
def maximum(x, y):
if x > y:
return x
else:
return y
#
print(maximum(2, 3))
• The pass statement: an empty block
def someFunction():
pass
9/12/2015 Learn to Program with Python 87
DocStrings
• Python has a nifty feature called
documentation strings, usually referred to by
its shorter name docstrings.
9/12/2015 Learn to Program with Python 88
Modules
• How to create modules that contains
functions and variables?
– create a file with a .py extension
– write the modules in the native language
• A module can be imported by another
program.
import sys
9/12/2015 Learn to Program with Python 89
Create a Modules
• Create a module named first_module.py
print("Hello World!")
• Create another file named first_hello.py
import first_module
Hello World!
9/12/2015 Learn to Program with Python 90
Modules
• Create a second_module.py
def hello():
print("Hello World!")
• Calling the function from hello2.py
import second_module
second_module.hello()
from second_module import hello
hello()
9/12/2015 Learn to Program with Python 91
A module’s __name__
• A module’s __name__
– Each module has a name and statement in a
module can find out the name of its module.
if __name__ = '__main__':
print('This program is being run by itself')
else:
print('I am being imported from another module')
9/12/2015 Learn to Program with Python 92
7. Data Structures
9/12/2015 Learn to Program with Python 93
Data Structures
• Python has built-in, dynamic data structures
or collections
– You basically never need to define your own
• Lists (approx. homogenous arrays)
• Tuples (approx. heterogeneous arrays)
• Dictionaries (key-value mappings)
• Sets (unique values)
9/12/2015 Learn to Program with Python 94
Lists are Variable Length, Same Types
• List holds an ordered collection of items
enclosed in square brackets.
• Lists are mutable, and their elements are
usually homogeneous and are accessed via
iteration.
shoplist = ['apple', 'mango', 'carrot', 'banana']
for item in shoplist:
print(item, end=' ')
print('My shopping list is: ', shoplist)
shoplist[0] = 'strawberry'
9/12/2015 Learn to Program with Python 95
Lists are Variable Length, Same Types
names = ["Matthew", "Mark", "Luke"]
names.append("John")
# Zero-indexed (but something better is coming up)
names[0]
# Convert other sequences to a list
x = list(y)
x = list(names)
9/12/2015 Learn to Program with Python 96
List Arithmetic
list1 = [1, 2, 3, 4]
list2 = ['I ate chocolate', 'and want more']
list3 = list1 + list2
print(list3)
9/12/2015 Learn to Program with Python 97
Tuples are Fixed-Length, Different Types
• Tuples are immutable, and their elements are
usually heterogeneous and are accessed via
unpacking or indexing.
shoptuple = ('apple', 'mango', 'carrot', 'banana')
for item in shoptuple:
print(item, end=' ')
print('My shopping list is: ', shoptuple)
#shoptuple[0] = 'strawberry'
9/12/2015 Learn to Program with Python 98
Tuples are Fixed-Length, Different Types
person = ("Simon", 180.0, 35)
person[0]
person[1]
# Convert a sequence to a tuple
x = tuple(y)
X = tuple(person)
9/12/2015 Learn to Program with Python 99
Dictionaries Map Keys to Values
• Dictionary is like an address-book and pair of
key and value.
• Key must be unique.
ab = { 'John' : '
[email protected]',
'Tony' : '
[email protected]'
}
ab['John']
ab['John'] = '[email protected]'
9/12/2015 Learn to Program with Python 100
Dictionaries Map Keys to Values
x = { "Rank": 7, "Score": 93.4 }
"Rank" in x
x["Rank"]
# Try x.keys(), x.values(), and
x.items()
9/12/2015 Learn to Program with Python 101
Sequences
• strings
• lists
• tuples
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
print(shoplist[0])
print(shoplist[-1])
print(shoplist[1:3])
print(shoplist[1:-1])
print(shoplist[2:])
print(shoplist[:])
9/12/2015 Learn to Program with Python 102
Sets Contain Unique Values
• Sets are unordered collections of simple objects.
# or set([1, 3, 3, 5, 7])
in
9/12/2015 Learn to Program with Python 103
References
• When you create an object and assign it to a
variable, the variable only refers to the object and
does not represent the object itself!
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
mylist = shoplist
del shoplist[0]
print(‘shoplist is: ‘, shoplist)
print(‘mylist is: ‘, mylist)
#
mylist = shoplist[:]
del mylist[0]
print(‘shoplist is: ‘, shoplist)
print(‘mylist is: ‘, mylist)
9/12/2015 Learn to Program with Python 104
More About Strings
• Strings are also objects and have methods
which do everything from checking part of a
string to stripping spaces!
• The strings that you use in program are all
objects of the class str.
• For a complete list of such methods, see
help(str).
• Code: ex_str_methods.py
9/12/2015 Learn to Program with Python 105
8. Input Output
9/12/2015 Learn to Program with Python 106
Input from User
• Input from User
something = input('Enter text: ')
print(something)
9/12/2015 Learn to Program with Python 107
Files
• Reading from a file
• code: ex_using_file.py
f = open('myinput.py')
while True:
line = f.readline()
if len(line) == 0: # EOF
break
print(line, end='')
f.close()
9/12/2015 Learn to Program with Python 108
Writing to a File
• Writing to a file
f = open('myoutput.txt', 'w')
f.write('Hello, World!')
f.close()
9/12/2015 Learn to Program with Python 109
Pickle
• Python provides a standard module called
pickle using which you can store any Python
object in a file and then get it back later. This
is called storing the object persistently.
• code: ex_pickling.py
9/12/2015 Learn to Program with Python 110
Optional Advanced Subjects
9/12/2015 Learn to Program with Python 111
9. Object Oriented
Programming (OOP)
9/12/2015 Advanced Python 112
The Characteristics of OOP
• Objects
– We live in an object-oriented world.
– An object is a structure for incorporating data and
methods/functions/procedures for working with
that data.
• Abstraction
– high level of an object
• Encapsulation
– no direct access to the data is granted
9/12/2015 Learn to Program with Python 113
The Characteristics of OOP
• Polymorphism
– two different objects have the same methods,
e.g., print()
• Inheritance
– parent and child
• Aggregation
– an object consists of a composite of other objects
9/12/2015 Learn to Program with Python 114
Object Oriented Programming
• Object Oriented Programming paradigm:
combines data and functionality and wrap it
inside something called an object.
• Python is strongly object-oriented in the sense
that everything is an object including numbers,
strings and functions.
• Classes and objects are the two main aspects
of object oriented programming.
9/12/2015 Advanced Python 115
Classes and Objects
• A class creates a new type where objects are
instances of the class.
• Python refers to anything used in a program as an
object.
• Objects can
– store data using variables or fields
• instance/object variables: variables belong to each
instance/object of the class
• class variables: variables belong to the class itself
– have functionality by using functions or methods
9/12/2015 Advanced Python 116
Classes and Functions
• Objects with Classes
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def birthday(self):
self.age = self.age + 1
#
ben = Person("Ben", 10)
print(ben.name, ben.age)
9/12/2015 Advanced Python 117
Self
• Class methods have only one specific
difference from ordinary functions - they must
have an extra first name that has to be added
to the beginning of the parameter list, but you
do not give a value for this parameter when
you call the method, Python will provide it.
• This particular variable refers to the object
itself, and by convention, it is given the name
self.
9/12/2015 Learn to Program with Python 118
The __init__ Method
• The __init__ method is run as soon as an
object of a class is instantiated and it does any
initialization.
• code: ex_person.py
9/12/2015 Advanced Python 119
Object Methods
• classes/objects can have methods just like
functions except that we have an extra self
variable.
• code: ex_method.py
9/12/2015 Learn to Program with Python 120
Class and Object Variables
• There are two types of fields (variables):
– Class variables: variables belong to the class itself.
They are shared and can be accessed by all
instances of that class. There is only one copy of
the class variable.
– Object/Instance variables: variables belong to
each instance/object of the class. Each object has
its own copy of the field. They are not shared.
• code: ex_objvar.py
9/12/2015 Learn to Program with Python 121
Inheritance
• One of the major benefits of object oriented
programming is reuse of code and one of the
ways this is achieved is through the inheritance
mechanism. Inheritance can be best imagined as
implementing a type and subtype relationship
between classes.
• polymorphism: where a sub-type can be
substituted in any situation where a parent type
is expected i.e. the object can be treated as an
instance of the parent class.
• code: ex_inherit.py
9/12/2015 Learn to Program with Python 122
Derived Classes Example
Person
Parent
Daughter Son
9/12/2015 Learn to Program with Python 123
Derived Classes Example
• Derived Classes
class Parent(Person):
def __init__(self, name, age):
Person.__init__(self,name,age)
self.children = []
def add_child(self,child):
self.children.append(child)
def print_children(self):
print(“The children of “, self.name, “ are:”)
for child in self.children:
print(child.name)
• code: ex_parent_child.py
9/12/2015 Advanced Python 124
Inheritance Example
SchoolMember
Teacher Student
9/12/2015 Learn to Program with Python 125
10. Exceptions
9/12/2015 Advanced Python 126
Exceptions
• Exceptions occur when certain exceptional
situations occur in your program.
9/12/2015 Learn to Program with Python 127
Errors
• Print('Hello World')
• print('Hello World')
9/12/2015 Learn to Program with Python 128
Handling Exceptions
• Handling Exceptions
– code: ex_try_except.py
try:
text = input(‘Enter something: ‘)
except EOFError:
print(‘It was an EOF’)
else:
print(‘You entered {0}’.format(text))
9/12/2015 Advanced Python 129
Raising Exceptions
• Raising Exceptions
• The error or exception that you can raise
should be class which directly or indirectly
must be a derived class of the Exception
class.
• code: ex_raising.py
raise EOFError()
9/12/2015 Advanced Python 130
Try ..Finally
• Try ..Finally
• code: ex_finally.py
try:
# do something
except EOFError:
# process the exception
finally:
# clean up
9/12/2015 Advanced Python 131
With Statement
• Acquiring a resource in the try block and
subsequently releasing the resource in the
finally block is a common pattern. Hence,
there is also a with statement that enables
this to be done in a clean manner.
• code: ex_using_with.py
with open(“poem.txt”) as f:
for line in f:
print(line, end=‘’)
9/12/2015 Advanced Python 132
11. Standard Library
9/12/2015 Advanced Python 133
Standard Library
• The Python Standard Library contains a huge
number of useful modules and is part of every
standard Python installation.
– https://docs.python.org/3/library/index.html
• Some of the commonly used modules in the
Python Standard Library
– sys
– logging
– urlib
– json
9/12/2015 Advanced Python 134
sys module
• The sys module contains system-specific
functionality. We have already seen that the
sys.argv list contains the command-line
arguments.
• code: ex_versioncheck.py
9/12/2015 Learn to Program with Python 135
logging module
• logging module displays debugging messages.
• code: ex_use_logging.py
9/12/2015 Learn to Program with Python 136
urlib and json modules
• Use urllib and json modules to access the web.
• code: ex_yahoo_search.py
9/12/2015 Learn to Program with Python 137
Special Methods
• Special Methods
– __init__
– __del__
– __str__
– etc.
• Single Statement Blocks
if flag: print(‘Yes’)
9/12/2015 Advanced Python 138
12. More
9/12/2015 Learn to Program with Python 139
More
• Passing tuples Around
def get_error_details():
return(2, ‘second error details’)
errnum, errstr = get_error_details()
9/12/2015 Advanced Python 140
Lambda Forms
• Lambda Forms: to create new function objects
and return them at runtime
def make_repeater(n):
return lambda s: s * n
twice = make_repeater(2)
print(twice(‘word’))
print(twice(5))
9/12/2015 Advanced Python 141
What Next?
9/12/2015 Learn to Program with Python 142
What Next
• PyGame
• Raspberry Pi
• Minecraft Mods with Python
• Web Development with Django
• Data analysis, machine learning, etc.
• System admin, engineering, finance, etc.
9/12/2015 Learn to Program with Python 143
What Next
• Example Code
• The best way to learn a programming language is
to write a lot of code and read a lot of code:
– The PLEAC project
– Rosetta code repository
– Python examples at java2s
– Python Cookbook is an extremely valuable collection
of recipes or tips on how to solve certain kinds of
problems using Python. This is a must-read for every
Python user.
9/12/2015 Learn to Program with Python 144
What Next
• Microsoft YouthSpark
• Find Your Passion
• Girls Who Code
• AP Computer Science (College Board)
– AP Computer Science A
– AP Computer Science Principles (coming fall 2016)
9/12/2015 Learn to Program with Python 145
Class Projects
9/12/2015 Learn to Program with Python 146
Team Members
• Three members per team
• Team Discussion
– Discuss the strategy of solving the problem
– Design the solution
– Pick the member roles
• Member Roles
– Developer 1: tell the coder what to write
– Developer 2: type in the code and check the code
– Tester 1: test the code to ensure the quality
9/12/2015 Learn to Program with Python 147
Temperature Converter
• Temperature Converter
– Celsius = (Fahrenheit-32)*5/9
– Fahrenheit = (Celsius*9/5)+32
9/12/2015 Learn to Program with Python 148
Compound Interest
• Compound Interest
9/12/2015 Learn to Program with Python 149
Mortgage Loan Calculator
• Mortgage Loan Calculator
• M = P [ i (1 + i)^n ] / [ (1 + i)^n – 1]
– M: monthly payment
– P: principal balance
– i: monthly interest rate
– n: number of monthly payments
– ^: power
9/12/2015 Learn to Program with Python 150
Drawing with Turtle
• Turtle graphics for Tk
– https://docs.python.org/3/library/turtle.html
• Turtle star
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
9/12/2015 Learn to Program with Python 151
Currency Converter
• Currency Converter
9/12/2015 Learn to Program with Python 152
Metric Converter
• Metric Converter
9/12/2015 Learn to Program with Python 153
Guess the Number
• http://inventwithpython.com/chapter4.html
• You’re going to make a “Guess the Number”
game. The computer will think of a random
number from 1 to 20, and ask you to guess it.
The computer will tell you if each guess is too
high or too low. You win if you can guess the
number within six tries.
– Source code: guess.py
Python 101: Invent Your Own Computer
9/12/2015 154
Games with Python
Dragon Realm
• http://inventwithpython.com/chapter6.html
• In the “Dragon Realm” game, the player is in a
land full of dragons. The dragons all live in caves
with their large piles of collected treasure. Some
dragons are friendly and share their treasure with
you. Other dragons are hungry and eat anyone
who enters their cave. The player is in front of
two caves, one with a friendly dragon and the
other with a hungry dragon. The player must
choose between the two.
– Source code: dragon.py
Python 101: Invent Your Own Computer
9/12/2015 155
Games with Python
Hangman
• http://inventwithpython.com/chapter8.html
• Hangman is a game for two people usually played with
paper and pencil. One player thinks of a word, and
then draws a blank on the page for each letter in the
word. Then the second player tries to guess letters that
might be in the word.
• If they guess correctly, the first player writes the letter
in the proper blank. If they guess incorrectly, the first
player draws a single body part of the hanging man. If
the second player can guess all the letters in the word
before the hangman is completely drawn, they win. But
if they can’t figure it out in time, they lose.
9/12/2015 Learn to Program with Python 156
Flow Chart for Hangman
9/12/2015 Learn to Program with Python 157
Hangman
• http://inventwithpython.com/chapter9.html
• Source code: hangman.py
9/12/2015 Learn to Program with Python 158
More
• Invent Your Own Computer Games with
Python
– http://inventwithpython.com/chapters/
9/12/2015 Learn to Program with Python 159
And Your FUN Projects Are…
• …
9/12/2015 Learn to Program with Python 160
Python Graphic User
Interface (GUI) with tkinter
9/12/2015 Learn to Program with Python 161
Python Graphic User Interface (GUI)
with tkinter
• Graphical User Interface (GUI) with Tk &
tkinter
– https://docs.python.org/3/library/tk.html
• Simple python tkinter program
import tkinter
l = tkinter.Label(text = "See me?")
l.pack()
l.mainloop()
9/12/2015 Learn to Program with Python 162
Q&A
9/12/2015 Learn to Program with Python 163
Thank You!
9/12/2015 Learn to Program with Python 164
Learn to Program with Python
Chia James Chang
[email protected] Microsoft Corp.
Volunteer teaching @ROLF, ROLCA, CoderDojo Silicon Valley