Download Introduction: first taste of Python

Document related concepts
no text concepts found
Transcript
Introduction to Programming
Applications with Python
Ralf Y. Lin| 林悦辰
[email protected]
04/16/2011
Pre-lecture Survey
2017/4/30
Ralf Y. Lin
Intro to Programming Applications
With Python
2
Pre-lecture Survey
• Tell me what you already have in mind
about the content in the 3 hour course.
– basic programming concepts (e.g., command
line and multi line)
– learn how to write basic programs.
– python applications (make a
website???...probably not today….)
2017/4/30
Ralf Y. Lin
Intro to Programming Applications
With Python
3
Agenda
• The Programming World
10min
• First Taste of Python
15min
• Variables and Functions
20min
• Selective Execution
30min
• Loops and iterations
30min
• Class & The Turtle Module 20min
• Extensions: Files
20min
•2017/4/30
More Applications remaining time, if any 4
The Programming World
Introduction to Programming
Applications with Python
The World of
Computer
Languages
2017/4/30
6
Objectives
• It is assumed that you have only basic computer
skills, such as file editing, file management, and
web browsing.
• You will learn how to write interesting programs
in the productive, easy-to-use programming
language, Python.
2017/4/30
7
Why Start with Python?
• Currently, many introductory computing courses
are based on a purely commercial language.
• Java
• C++
• C#
• VB.Net
2017/4/30
8
Why Start with Python?
• What is problematic with purely commercial languages?
• Introductory computing education was once dominated by
languages designed exclusively for education.
• Python is neither a purely educational language nor a
purely commercial one, but a hybrid language that can be
used well for either purpose.
2017/4/30
9
Install Python 3.1.2
• Download Python 3.1.2 (see next)
• Run the installation program:
– python-3.1.2.msi
• Follow the steps (as simple as clicking the
“next” button a few times). For more
detailed instructions, refer to book “Invent
Your Own Computer Games with Python”.
• NOTE: Python is cross-platform! You can
also install Python on Max OS, Linux, etc.
2017/4/30
10
First Taste of Python
Introduction to Programming
Applications with Python
Let’s Do Some Math
2017/4/30
12
Print Function
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Optional keyword arguments:
– file: a file-like object (stream); defaults to the current sys.stdout.
– sep: string inserted between values, default a space.
– end: string appended after the last value, default a newline.
2017/4/30
13
Print Function (Cont’d)
•
•
•
•
•
•
>>> print( 'doesn\'t‘ )
>>> print( "doesn't“)
>>> print( '"Yes," he said.' )
>>> print( "\"Yes,\" he said.“)
>>> print( '"Isn\'t," she said.‘)
>>> print( ‘this is the slash \\.’ )
2017/4/30
14
2017/4/30
Ralf Y. Lin
Intro to Programming Applications
With Python
15
2017/4/30
Ralf Y. Lin
Intro to Programming Applications
With Python
16
Comments
• Something to be ignored by the computer
• This is useful for someone (you or
somebody else) to understand what’s
going on.
• In Python, a comment starts with a ‘#’ that
is NOT between quotes, and continue till
the end of a line.
• >>> #this is a comment
• >>> “#this is not!” #but this is!
2017/4/30
17
Operate on strings
• Glue strings together
– >>> “Hello”+”World”+”!”
• Repeat strings
– >>> “Hello!” * 3
2017/4/30
18
Slicing Strings
• >>>”Hello!”[3]
• >>>”Hello!”[0:3] #the first three chars
• >>>”Hello!”[:3] #the missing starting index
=0
• >>>”Hello!”[3:] #everything after the third
char
• >>>”Hello!”[:] #guess what is this?
• >>> “Hello!”[-1] #Guess?
2017/4/30
19
Indexing hint
• One way to remember how slices work is to
think of the indices as pointing between
characters, with the left edge of the first
character numbered 0. Then the right edge of
the last character of a string of n characters has
index n, for example:
• +---+---+---+---+---+
|H |e |l | p |A|
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
2017/4/30
20
Ask for help from Python
• At the prompt, type “help()” to get into
interactive help mode.
– Read the welcome message carefully.
– Explore the interactive help.
– Type “quit” to quit the interactive mode.
• At the prompt, type help(something) for
help about “something”.
2017/4/30
21
Hello World!
• Here is a very short program:
>>> print(“Hello World!”)
Hello World!
-- You have just wrote your fist program!
-- it uses the “print” function provided by Python
by default (which is also called the built-in) to
print out something.
-- the thing to be printed is a string (quoted).
2017/4/30
22
Variables and Functions
Introduction to Programming
Applications with Python
Sample Program: Temperature Converter
The ‘def’ keyword
• The ‘def’ keyword starts a definition of a
function, it works like this:
def <name> ( <parameters> ) :
<statements>
Function
body
Have you noticed the indentations here?
They are VERY IMPORTANT! All these
statements must be indented and aligned
to indicate that they are a single group of
statements (as the function body) that
defines this function.
Function
header
The input(…) function
• This is an input statement (inside an
assignment statement)
• And input(…) is a built-in function
• It returns the user input as a string!
• Use help(input) in interactive mode to
obtain more information on it
• In IDLE, when you type “input(“, a tip will
show up, giving you some brief information
about it.
Working with Numbers
The ‘return’ Keyword
• When you define a function, the function can
return a value,
def fun(x): return x*x
• Or multiple values,
def fun(t): return t+1, t+2, t+3
• Or nothing (then object ‘None’ is returned)
def fun(): return
• The return statement returns with a value
from a function. return without an expression
argument returns None. Falling off the end of
a function also returns None.
Test Your Design
• Second Counter
– Given seconds, minutes, and hours, count the
total of all seconds. Please do it in two ways.
• Print
• Return
Selective Execution
Introduction to Programming
Applications with Python
Example: Conversion Selector
Example: Conversion Selector
Sample invocations of the conversion selector program
The select() function
First invokes the helper
function “displayMenu”
to display the menu.
The select() function
Second, the select
function inputs a user
choice.
The select() function
“elif” is an
abbrev. of
“else if”
Third, the select() function
selects what to do based on
the user choice.
The select() function
Last, the select()
function prints “Byebye.”
“if” statement -- syntax
• “if” statement always
starts with “if”
• After “if” comes a
condition, terminated by a
colon “:”
• Then a block of
statements for that
condition (indented).
• Dedentation indicates the
end of the block.
• This is an if-clause
“if” statement -- syntax
• Optionally, after the ifclause, there may be
multiple elif-clauses,
which start with “elif”
• The “elif” must start at the
same indentation level
• After “elif” comes a
condition, terminated by a
colon “:”
• Then a block of
statements for that
condition (indented).
• Dedentation indicates the
end of the block.
“if” statement -- syntax
• Finally, there can be one
optional else-clause,
which starts with “else”
• The “else” must start at
the same indentation
level as the “if”
• After “else” comes NO
condition, immediately
followed by a colon “:”
• Then a block of
statements for “else”
• Dedentation indicates the
end of the block.
“if” statement -- semantics
• Execute the first block
of statements for
which the condition is
true, then exit the “if”statement.
• Note: for the elseclause, as there is no
condition, it is always
true (else: if all the
above conditions
have failed).
Flow Chart for if statment
2017/4/30
Ralf Y. Lin
Intro to Programming Applications
With Python
41
Test Your Design
• The following sample problem requires a multiple
selection if-statement.
–
–
–
–
Develop a function that will:
Input taxable annual income.
Determine the applicable tax rateand calculate the taxdue.
Output the tax due.
• Use the following Tax Table:
In-place operators
• +=, -=, *=, /=, //=, %=, **=
–
–
–
–
–
–
–
No space in between!
X += 3  X = X+3
X *= 3  X = X*3
X /= 3  X = X/3
X //= 3  X = X//3
X %=3  X = X%3
X**=3  X = X**3
• Advantage: saves typing it twice!
– Less is better than More (less chance of errors)
One-Way Selection
• Trace the execution of all statements
below using various user inputs.
Nested If-statements
• All clauses of an “if”-statement must start
with the same indentation.
• An “if”-statement, though occupies multiple
lines, is a single statement in concept. In
fact, it is a complex statement.
• Thus, it is no surprise that an “if”statement can contain other “if”statements.
Nested If-statements
Comparisons
Loops and iterations
Introduction to Programming
Applications with Python
Problem: Repetitive Conversions
• Consider the following programming problem. Develop
a Conversion Repetitions program that will:
– Display a menu of three choices:
• Fahrenheit to Celsius
• Celsius to Fahrenheit
• Exit the menu choice
– Ask the user to make one choice from the menu
– Depending on the particular user choice, do one of the
following:
• Perform the conversion chosen by the user then
repeat all of the above steps, or
• Exit the menu repetitions, if that was what the
user chose.
Problem: Repetitive Conversions
• The menu may look like this:
The Major Function
Whilestatemen
t.
This statement is executed only
after the while-statement is finished.
Let’s run it in IDLE (pressing F5)
While-statement: syntax
The while-clause.
It is required. It
consists of a
header and a
body. The header
must begin with
the keyword
‘while’, followed
by a condition,
ended with a
colon ‘:’.
The body is a
block of
statements,
indented and
aligned.
While - statement:
Consists of one required
while-clause, optionally
followed by one elseclause.
While-statement: Semantics
• The execution (no break and continue):
– (1) Start by testing the while-condition, if it is
False, execute the else-clause if there is one,
and exit the while-statement.
– (2) If it is True, execute the body of the whileclause, and after finishing the last statement
in the body, loop back to the beginning ,
repeat (1).
Flow Chart-While Statement
2017/4/30
Ralf Y. Lin
Intro to Programming Applications
With Python
54
Break and Continue
• Similar to the break and continue in for-loops.
• The ‘break’ statement, if executed, will exit
the whole while-statement immediately (the
else-clause won’t be executed).
• The ‘continue’ statement, if executed, will
loop back to the beginning of the whilecondition immediately without executing the
remaining statements after it in the whilebody. The else-clause will still be executed if
the while-condition becomes False.
Implement repeat() another way
The Boolean literal
True is a legitimate
Boolean expression. Of
course, this literal
always remains true; it
will never become false.
Interrupt
Pretest, Interrupted, and Hybrid
While-loops
• We distinguish between these 3 types of loops
depending on their termination mechanisms:
– A pretest loop always terminates when the condition
of its while-clause evaluates to false(conversions.py).
• The term pre-test has been adopted to stress the fact that the
test precedes the execution of the loop body.
– An interrupted loop always terminates with the
execution of a break-statement(repeats.py).
– A hybrid loop is a combination of pretest and
interrupted loops and can terminate either way in
individual executions.
Test your Design
• Develop a function named ‘scores’ that
will:
– Input a sequence of integer scores
(terminated by the empty string ‘’).
– Count the number of received scores.
– Find the average score.
– Output the number of all scores and the
average score.
Input Data Validation
• A variety of useful validation and recovery procedures
can be implemented using while-loops.
• As a useful case study, consider a single wages
function that will:
– Input an employee number, hours worked during a week,
and hourly pay rate.
– Validate input data according to the following rules:
• Employee number must be between 1000 and 9999.
• Hours worked must be between 0 and 168.
• Pay rate must be between 10 and 80.
– Calculate gross wages(before taxes) by multiplying hours
by rate.
– Provide adequate output.
Input Data Validation
Nested Loops
• The body of a while-statement can contain
inner while-statements.
• These interior statements may contain
other inner statements, and so on.
• The level of nesting statements is
unlimited.
Nested Loops: Example
Obtain K validated samples from
input.
What if I need K
unique samples?
Casino Roulette Simulator
• Casino roulette is a gambling game in
which players bet on which slot of a
revolving wheel a small ball will come to
rest in.
• Simulating the game with a computer
program is not only harmless, but is also
educational and possibly entertaining.
The Simulator
Case Study: Binary Search
• How to guess a secret number in a certain
range? You always have feed back on
how your guess is related to the secret
number.
– You can ask how your guess is related to the
middle of the range, to find out which of the
two half ranges the secret number belongs
to.
– Once a smaller range is determined, you can
continue on, until the range contains only one
number!
Binary Search Method
• The number guessing method (outlined in the previous
slide) is an informal example of general problem
solving method called binary search.
• You can apply binary search to very large ranges of
data and succeed in small number of steps.
– Consider for example the problem of guessing a secret
integer number that is anywhere between 1 and 1,024.
– Binary search takes only 10 partitioning steps to reduce a
range of 1024 numbers to a range of just one number.
– A range of about one million numbers is reduced to one
single number by only 20 partitioning steps.
– In general, it will take you no more than N steps to guess
an arbitrary secret number in range(1, 2**N).
Binary Search
Class: The Turtle Module
Introduction to Programming
Applications with Python
objects
• Everything in Python is an Object
– Numers, strings, lists, functions, …
– In the memory, they are just a bunch of 0’s and 1’s
– The identity of an object tells us it is a physical entity living
in the memory as a chunk of 0’s and 1’s. If two objects
have the same identity, then they are the same chunk of
memory.
– The interpretation (the meaning) of those 0’s and 1’s
depends on the type of the object.
• When you are given only a bunch of 0’s and 1’s, it is impossible
to tell what it represents without knowing what kind of object it
is.
– Objects can come with some methods to do computations
on them, which also depend on the type of the object
• There is str.upper(), but we don’t have int.upper()
types
• It is the type that gives meaning
(interpretation) to the 0’s and 1’s in
memory. The meaning/interpretation is
known as the value of the object.
• It is the type that provides methods to
manipulate the 0’s and 1’s in memory.
– Later on, we will see that operators are
methods
• A type provides a blueprint for objects of it.
classes
• A class is a type (a concrete type).
– int, str, float, list, tuple, dict, … they are all
classes
>>> type(0) is int #int is the class for 0
• For objects in a class, the class defines
– What values they can take
– What methods they can have (collection of
functions that manipulate the value of the object)
• An object of a class is also called an instance
of the class (i.e. a concrete example from the
class).
– So the object 0 is an instance of class int
Case Study: 2D vector
• We will define a new class: Vec2D
• An instance of Vec2D is a vector in
the 2-dimensional space, starting
from (0,0), pointing to a point (x,y) in
the space.
• We should be able to find its length,
which is square root of (x*x + y*y).
• We should be able to scale it by a
real number s: after scaling, it points
to the point (x*s, y*s).
• We will allow two vectors to add up.
Design
• Values to be included in a 2-D vector
– The coordinates of the end point: x, y
• Methods to be provided
– length(…) #find length of the vector
– scale(…) #scale the vector by a real number
– add(…) #add two vectors together
– __init__(…) #initialize a vector instance
Defining a Class
#new file here: vec2d.py
class Vec2D: #the header.
“the doc string for the class”
def __init__(self, x, y):
“initialize the instance self with x,y”
self.x, self.y = float(x), float(y)
#no need to return anything here
#Comment: the ‘self’ parameter is referring to the created
instance itself. All methods that manipulate the instance itself
will be passed the instance as the first argument, named ‘self’
by tradition (follow it for better readability -- others will find it
easier to read).
Instantiate a Vector
>>> v = Vec2D(2, 3)
#the arguments will be passed to
#the __init__ method we just defined
>>> v.x, v.y
# all seems fine so far, let’s continue
# it is good to develop you program
incrementally: do a little bit, then test it. Don’t
go further unless all seems OK so far.
Length method
# new file: vec2d.py
class Vec2D:
…
def length(self):
“return the length of the vector”
from math import sqrt
return sqrt(self.x*self.x - self.y*self.y)
Test Again
>>> v = Vec2D(3, 4)
>>> v.length()
# now we have trouble: a ValueError
# reason: square root of negative numbers
# seen from the error message: location of
error, type of error, and an error message.
scale and add
class Vec2D:
…
def scale(self, s):
self.x *= s
self.y *= s
def add(self, v):
self.x += v.x
self.y += v.y
# now test it again.
The __repr__ special method
• If we want to replace those ugly
representation of our Vec2D objects from
python shell, we can define a special
method.
• If we implement the __repr__ special
method, we will have a nicer string
representation.
– When we didn’t implement __repr__, a default
one is provided (inheritance, next lecture),
giving us an ‘ugly’ string representation.
__repr__
class Vec2D:
…
def __repr__(self):
return “Vec2D({},{})”.format(self.x, self.y)
#=========test starts here===
>>> v = Vec2D(3,4)
>>> repr(v)
>>> print(v)
>>> v
>>> eval( repr(v) )
Adding Vec2D vectors by ‘+’
• The operator ‘+’ is done by the special
method __add__.
>>> x=1; x.__add__(2)
>>> 2 .__add__(3) # try 2.__add__(3)?
class Vec2D:
…
def __add__(self, v):
#add together, return a new instance
return Vec2D(self.x+v.x, self.y+v.y)
The Turtle Module
• LOGO: Logic Oriented Graphic Oriented
– Created in 1967 for educational use
– Famous for it’s turtle graphics
• Python turtle module
– Best way to teach kid/rookies python!
– One module, 80+ methods.
– In IDLE, press F1, search for “turtle” there.
The Basic Model
• It works like a drawing pad toy for kids
• There is a canvas with one or more pens
– They are called turtle pens (crawling around and
leaving trails behind if the pen is down – touching
the canvas). Use penup(), pendown() to control.
– Turtle pens have sense of front/rear, so you can
• Move by: forward(distance), backward(distance)
• Turn by: left(angle), right(angle)
• The goto(x, y) moves to an absolute position (x,y).
Digital graphics: What is a
pixel?
• Your camera, LCD screen, printer, copier
machine – they all have a resolution.
– That basically says how many small dots per
row and how many dots per column. Those
tiny dots are called pixels.
• If you resolution is 1080X720, that means …
– Each pixel will show a color
– Together, all the pixels make a display.
– The continuity/smoothness is an illusion.
Manipulating the Turtle
>>> from turtle import *
>>> shape( “turtle” ) #the
default pen
>>> shapesize(5)
>>> forward( 30 )
>>> back( 30 )
>>> left (90)
>>> fd(30)
>>> goto(-30, 0)
>>> heading()
>>> setheading(-90)
>>> pen = Pen()
>>> p = Pen()
>>> p.left(20)
>>> p.pensize(30)
>>> p.left(20)
>>> p.shapesize(10)
>>> q = Pen()
>>> q.right(40)
>>> q.shapesize(10)
>>> q.fd(160)
>>> p.back(60)
The circle function
>>> q.circle(50, 360, 5)
>>> q.circle(50, 720, 5)
>>> q.fillcolor(‘blue’)
>>> q.begin_fill()
>>> q.circle(20, 360, 5)
>>> q.filling()
>>> q.end_fill()
>>> q.filling()
>>> q.fillcolor(‘pink’)
>>> q.begin_fill()
>>> q.left(180)
>>> q.circle(40, 720, 5)
>>> q.end_fill()
>>> q.fillcolor(.3, .7, .5)
>>> q.begin_fill()
>>> q.circle(40, 72, 10)
>>> q.end_fill()
Colors
• A pixel has a color. Here is how colors are
represented.
• Any color is a mixture of red, green and blue (RGB).
• This is specified by three numbers in the range of 0 to
1.
–
–
–
–
1,0,0 is red;
0,1,0 is green;
0,0,1 is blue
0,0,0 is black, and
1,1,0 is yellow
0,1,1 is cyan (aqua)
1,0,1 is magenta (hot pinky purple)
1,1,1 is white
• Different shades can be created by mixing the levels
– (0.5,0,0) for example is dark red; (1,0.5,0.5) would be pink
• Those color names can be used to specify a color in
turtle. Or you may supply the RGB components.
Demo I
>>> from turtle import *
>>> pensize(3)
>>> showturtle()
>>> shape(‘turtle’)
>>> for r in range(
...
20, 200, 20):
…
circle(r)
>>> bye() #close canvas
Demo II
>>> from turtle import *
>>> shape("circle")
>>> pu() #penup, no trail
>>> goto(0, 100)
>>> fillcolor("red")
>>> shapesize(5, 1, 4)
>>>
>>> for i in range(72):
...
forward(12)
...
left(-5) #turn
...
tilt(7.5) #accumulative
...
_ = stamp() #dummy
Demo III
>>> from turtle import *
>>> shape(‘triangle’)
>>>
f,phi=.83282,6.89637
>>> s, c = 20, 1
>>> for i in range(20):
shapesize(s)
fillcolor(c,.5,1-c)
d=stamp()
s*=f; c*=f
right(phi)
Many More Demos
• Download the demo
from the course ftp
• Or download from the
internet:
• http://code.google.co
m/p/python-turtledemo/downloads/list
• Download the file:
TurtleDemo-1.0.0-py3.x.zip
• Unzip the archive and
run the turtledemo.py file.
• Let see some examples.
–
–
–
–
–
–
Elementary: Teddy cat
Python31demo: clock
Games: tangram.py
Python31demo: Nim
Python31demo: paint
Python31demo: round
dance
– Games: moorhuhn
– And many more …
Case Study: Concentric Circles
• In Turtle window,
• Use classes to implement it
draw some
– A ConcentricCircles class
• Represent a set of concentric
concentric circles
circles at a certain location.
with different radius
and colors.
• Can draw all the circles together
• Colors will be
• What information do we need to
randomly chosen.
know?
• Wait some time and
show another set of
– A Demo class
them. Each time the
• register stage information, to
configure the circles.
colors will likely to be
different.
• Can organize the whole show.
Extensions: Access Files
Introduction to Programming
Applications with Python
Accessing Files on the Web
• A Web file is on the Internet, located by a URL
– The file may be static, or it may be generated on the fly.
• Use urlopen in urllib.request module to open a Web
file. Here ‘urllib’ is a package (folder).
• Once successfully opened, we can read it like a file.
• Use the io.TextIOWrapper if it is a text file.
>>> from urllib.request import urlopen
>>> from io import TextIOWrapper as tiow
>>> with tiow(urlopen('http://www.python.org')) as htm:
print(htm.read())
Case Study: Getting Stock
Quotes
• What is a stock quote?
– A stock quote is the price at which the last trade of a
particular stock took place.
• Currently, in the United States, stocks are traded in
real time, over computer networks.
– Stock quotes are therefore known in real time, as trades
occur.
– Many web hosts offer free or subscription stock quotes in
real time or with a minimal delay.
• Free stock quotes are available, with a delay of
approximately 15-20 minutes, at finance.yahoo.com.
– These stock quotes are a dynamically generated resource
that is represented in CSV format.
– http://www.codeproject.com/KB/aspnet/StockQuote.aspx
Case Study: CandleSticks
•
•
Candlesticks are usually
composed of the body (black or
white), and an upper and a lower
shadow (wick): the area between
the open and the close is called
the real body, price excursions
above and below the real body are
called shadows.
To better highlight price
movements, modern candlestick
charts (especially those displayed
digitally) often replace the black or
white of the candlestick body with
colors such as red (for a lower
closing) and blue or green (for a
higher closing).
CandleSticks
• We will develop a program that can download
the trading data from Internet and draw a
candlestick chart of the stock prices.
– We already know how to download CSV data
– Today we focus on how to draw such a chart
• We use the turtle module
• A CandleStick Chart contains many CandleSticks
• A CandleStick has a rectangle body (filled or unfilled)
and two shadows
• All can be drawn onto the canvas (a method)
Class Design
• So we will have a class Shape, as the parent
class for the CandleStick and the StockChart
– They all have a method ‘draw’
– But they will have different data
• They shall branch from Shape class
• They will draw themselves differently.
– The StockChart can let all the CandleStock instances draw
themselves.
• The Rect class sits between Shape and CandleStick
• Test Run and Code Explanation
References
•
•
•
•
Dive into Python
Invent with Python
A Byte of Python
Invent your own computer game with
Python
2017/4/30
Ralf Y. Lin
Intro to Programming Applications
With Python
99