Chapter 2 - Computer Science Department

Download Report

Transcript Chapter 2 - Computer Science Department

Python Programming:
An Introduction to
Computer Science
Chapter 2
Python Programming, 2/e
1
Objectives

To be able to understand and write
Python statements to output
information to the screen, assign values
to variables, get numeric information
entered from the keyboard, and
perform a counted loop
Python Programming, 2/e
2
The Software Development
Process

The process of creating a program is
often broken down into stages
according to the information that is
produced in each phase.
Python Programming, 2/e
3
The Software Development
Process


Analyze the Problem
Figure out exactly the problem to be
solved. Try to understand it as much as
possible. (done by instructor here)
Try doing a problem by hand to verify
you understand it – this also generates
some test data for later.
Python Programming, 2/e
4
The Software Development
Process

Determine Specifications
Describe exactly what your program will
do.


Don’t worry about how the program will
work, but what it will do.
Includes describing the inputs, outputs,
and how they relate to one another.
Python Programming, 2/e
5
The Software Development
Process

Create a Design



Formulate the overall structure of the
program. (done by individual /team here)
This is where the how of the program gets
worked out.
You choose or develop your own algorithm
that meets the specifications. This is
where you write pseudocode.
Python Programming, 2/e
6
The Software Development
Process

Implement the Design


Translate the design into a computer
language.
In this course we will use Python.
Python Programming, 2/e
7
The Software Development
Process

Test/Debug the Program



Try out your program to see if it worked.
If there are any errors (bugs), they need to
be located and fixed. This process is called
debugging. (using test cases done by
team here)
Your goal is to find errors, so try
everything that might “break” your
program! Don’t be afraid to Experiment!
Python Programming, 2/e
8
The Software Development
Process

Maintain the Program



Continue developing the program in
response to the needs of your users.
In the real world, most programs are never
completely finished – they evolve over
time.
Not done in this class
Python Programming, 2/e
9
Example Program:
Temperature Converter


Analysis – the temperature is given in
Celsius, user wants it expressed in
degrees Fahrenheit.
Specification



Input – temperature in Celsius
Output – temperature in Fahrenheit
Output = 9/5(input) + 32
Python Programming, 2/e
10
Example Program:
Temperature Converter

Design




Input, Process, Output (IPO)
Prompt the user for input (Celsius
temperature)
Process it to convert it to Fahrenheit using
F = 9/5(C) + 32
Output the result by displaying it on the
screen
Python Programming, 2/e
11
Example Program:
Temperature Converter

Before we start coding, let’s write a
rough draft of the program in
pseudocode


Pseudocode is precise English that
describes what a program does, step by
step.
Using pseudocode, we can concentrate
on the algorithm rather than the
programming language.
Python Programming, 2/e
12
Example Program:
Temperature Converter

Pseudocode:
1.
2.
3.

Input the temperature in degrees Celsius
(call it celsius)
Calculate fahrenheit as (9/5)*celsius+32
Output fahrenheit
Now we need to convert this to Python!
Python Programming, 2/e
13
Example Program:
Temperature Converter
#convert.py
# A program to convert Celsius temps to Fahrenheit
# by: Susan Computewell
def main():
celsius = eval(input("What is the Celsius
temperature? "))
fahrenheit = (9/5) * celsius + 32
print("The temperature is ",fahrenheit," degrees
Fahrenheit.")
main()
Python Programming, 2/e
14
Example Program:
Temperature Converter

Once we write a program, we should
test it!
>>>
What is the Celsius temperature? 0
The temperature is 32.0 degrees Fahrenheit.
>>> main()
What is the Celsius temperature? 100
The temperature is 212.0 degrees Fahrenheit.
>>> main()
What is the Celsius temperature? -40
The temperature is -40.0 degrees Fahrenheit.
>>>
Python Programming, 2/e
15
Elements of Programs





# at the start of a line is a comment
This line is ignored by the Python
interpreter
It is meant to be read by humans
Explain the code there, don’t repeat the
code!
Required in every program in this class!
Python Programming, 2/e
16
Elements of Programs

Names





Names are given to variables (celsius,
fahrenheit), modules (main, convert), etc.
These names are called identifiers
Every identifier must begin with a letter or
underscore (“_”), followed by any
sequence of letters, digits, or underscores.
Identifiers are case sensitive!
No spaces allowed in an identifier
Python Programming, 2/e
17
Elements of Programs

These are all different, valid names







X
Celsius
Spam
spam
spAm
Spam_and_Eggs
Spam_And_Eggs
Python Programming, 2/e
18
Elements of Programs



Some identifiers are part of Python itself.
These identifiers are known as reserved
words. (keywords) This means they are not
available for you to use as a name for a
variable, etc. in your program.
and, del, for, is, raise, assert, elif, in, print,
etc.
“Good programmers use names that
describe the item being named”
Python Programming, 2/e
19
Identifiers
• An identifier has to being with an
alphabetic character or the underscore
character _
• There can be more characters in the
identifier, those can be alphabetic,
numeric or the underscore character
• Upper or lower case alphabetic
characters are allowed
Identifiers

VALID
age_of_dog
PrintHeading

taxRateY2K
ageOfHorse
NOT VALID (Why?)
age#
2000TaxRate
Age-Of-Cat
in
Keywords
• Keywords define the language’s syntax
rules and structure
• Keywords cannot be used as variable
names.
Keywords






and
as
break
continue
def
elif else
finally for from global
in is
not or
pass
return
try
with
True
False
None
class
if
import
while
Data Types





Every program must deal with data
The data is usually described as a certain type
This type determines what you can do with the
data and how the data is stored
In Python basic types are integers (int), floating
point (float), strings and Booleans
The first two are numeric and can be used in
arithmetic, the last two are not
Integers vs. Floating point





Integers are numbers which have no decimals, no
fractions
They can be positive, negative, zero
Python can handle numbers of very, very large
magnitude
Floating point numbers are ones which have
fractions, like 3.14 and 2.0 and 5.2983841983
They are stored differently in the computer and
their arithmetic is done differently
Floating point numbers - storage



Each floating point number is stored in several
pieces. You can think of one as being written in
scientific notation, like 3.592 x 102 = 359.2
In Python this is written as 3.592e2 (the base is
assumed to be 10)
The 3.592 is the mantissa
Floating point numbers - storage



The 2 is the power or exponent – it can be
positive or negative. Positive powers make
numbers larger, negative powers make numbers
smaller (towards zero)
Example: 4.923e-3 = 0.004923
Example: 7.2341e10 = 72341000000
Strings

These data items are delimited by quotes, either
single quotes (‘) or double quotes (“)
(Delimited by means that they are enclosed by
the quotes, marked off by the quotes)
We will use them in many ways

simply as labels “Total of numbers”

variables like names and address

Examples: “Joe”, “12345923 adfa123.s8234&*”,
“”, ‘”hi” he said’


Booleans
•
Named after George Boole, English mathematician,
logician
•
Created Boolean algebra, a two-valued logic based on
True and False
•
The basis of all computer circuits (see EE 280)
•
In Python the Boolean constants are True and False –
note that these are not strings – no quotes
•
They can be assigned to variables, they can be output
•
They are used most often with if statements
Data type check






type() function to check type
Example:
type(3) : <class, ‘int’>
type(4.5): <class, ‘float’>
type(‘abc’): <class, ‘str’>
type(True): <class, ‘bool’>
Type casting




Sometimes you need a piece of data converted to
a different type
In Python you do a typecast to cause that to
happen
int(3.599) will give 3 – note that it throws away
the fraction, does not round it
float (4349) will give 4349.0 – it looks the same
but remember that it is stored differently in
memory
Type casting




float(“23.4”) will give 23.4, but float(“abc”)
will give a runtime error
The type converter float can turn an
integer, a float, or a syntactically legal
string into a float
x = 5.3 y = int(x)
makes y have the value 5, does NOT change
x’s value
Type cast for strings



str will turn a number into a string. This is handy
when you are using functions which require a
string as an argument
str(3.5) will give “3.5”
str(“abc”) will give “abc” – this one is silly but
Python allows it. If the data is already a string,
why make it a string again?
Input function
• The input function allows the user to provide
a prompt string.
• n = input("Please enter your name: ")
• It is very important to note that
the input function returns a string value.
• n = input("Please enter your age: ")
Typecasting with input function





Typecasting is used pretty often with the input
function
my_num = int(input(“Enter a number “))
This is the shorthand way of writing two
statements
my_data = input(“Enter a number “))
my_num = int(my_data)
Arithmetic operators



Some operators in Python will look familiar (+, -,
*, /)
Others are new to you (%, //, **)
All of these do work with numbers and produce
numbers
For any operator you need to
know





How many arguments does it have and what do
they mean
What data type are the arguments? (int, float,
string, etc.)
The semantics of the operator, which is what
does it do? What does it mean?
What data type does the operator return? NOT
always the same as the type of the arguments
What is its precedence or priority with other
operators?
Example: addition +





It has two arguments (we are talking about the
addition operator here, not the unary plus sign)
The arguments can be ints or floats
It produces the sum of the values of the two
arguments
It produces an integer if the arguments are both
integers, otherwise it produces a floating point
number
It is relatively low precedence, comes after * and
/
Other familiar operators



Multiplication * works on ints and floats,
produces an int if 2 int arguments, float
otherwise
Subtraction works similarly to
multiplication
Division / works on ints and floats, but
always returns a float
Operator Precedence



Precedence is same as in algebra,
multiplication and division higher than
addition and subtraction
If there are two operators in an expression
of the same level of precedence, they are
executed left to right in the expression
a + b + c is done as (a + b) + c
Operator Precedence
Operator
Description
()
Parentheses (grouping)
function( ) function call, execute a function and get what it
returns
**
Exponentiation (raise to a power)
*/
Multiplication, division
+ -
Addition, subtraction
=
Assignment
Python Programming, 2/e
41
Operator Precedence



Important!
principal = principal * (1 + apr)
is not the same as
principal = principal * 1 + apr
answer = 20 – ((5+3)/(5-1))
answer = 18
Python Programming, 2/e
42
New Operators // and %



// is similar to division but always gives the
whole number part of the quotient (result
of dividing)
If give two ints, will give an int, otherwise a
float
5 // 4 = 1, 5 // 4.0 = 1.0 (not 1.25)
New Operators // and %

% is the modulus operator, gives the remainder of
a division operation

If give two ints, yields an int, otherwise a float

13 % 4 = 1 (the remainder when 13 is divided by 4), 8 % 4
=0

These two operators have the same precedence
as multiplication and division
New Operator **







** means exponentiation
Has two arguments a ** b
a is the base, b is the power to raise a to
5 **3 = 5 * 5 * 5, 7 ** 2 = 7 * 7 = 49
The precedence is higher than the other
arithmetic operators
The base or power can be integer or float
As usual, if two int arguments, gives int result,
otherwise float
New operator **





Is right associative (different from all of the
other operators)
Associativity is only needed when the
operators in an expression have the same
precedence
4 ** 3 ** 2 = 4 ** (3 ** 2) = 4 ** 9 = 262144
But + , –, * , / are left associative
7 -4 + 1 = (7 -4) + 1 not 7 – (4+1)
Expressions




The fragments of code that produce or
calculate new data values are called
expressions
Expressions can be combined using
operators.
+, -, *, /, **
Spaces are irrelevant within an
expression- please use them for ease of
reading!
Assignment statements




Syntax is simple identifier = expression
Python does allow more than one identifier on
the left, see “Simultaneous Assignments” for
more information
Semantics: evaluate the expression on the right
and then assign the value to the identifier on the
left
The expression can be as simple as a literal or
more complex by using function calls, list
indexing, arithmetic operators, etc.
Assignment Statements



x = 3.9 * x * (1-x)
fahrenheit = 9/5 * celsius + 32
x=5
Python Programming, 2/e
49
Assignment Statements

Variables can be reassigned as many
times as you want!
>>>
>>>
0
>>>
>>>
7
>>>
>>>
8
>>>
myVar = 0
myVar
myVar = 7
myVar
myVar = myVar + 1
myVar
Python Programming, 2/e
50
Simultaneous assignments




(Only in Python) If you use more than one
identifier on the left hand side of an assignment
statement, you can store more than one thing.
Example: x, y = 5, 4
Semantics: x gets the 5 and y gets the 4
You have to be careful – If the right hand side
does not yield as many values as the left hand
side expects, it causes a crash.
Simultaneous Assignment

We can swap the values of two
variables quite easily in Python!

x, y = y, x
>>>
>>>
>>>
34
>>>
>>>
43
x=3
y=4
print (x, y)
x, y = y, x
print (x, y)
Python Programming, 2/e
52
Simultaneous Assignment


We can use this same idea to input
multiple variables from a single input
statement!
Use commas to separate the inputs
def spamneggs():
spam, eggs = int(input("Enter # of slices of spam followed by # of eggs: "))
print ("You ordered", eggs, "eggs and", spam, "slices of spam. Yum!“)
>>> spamneggs()
Enter the number of slices of spam followed by the number of eggs: 3, 2
You ordered 2 eggs and 3 slices of spam. Yum!
>>>
Python Programming, 2/e
53
Library – a group of prewritten functions and
predefined constants


Many actions are frequently done in
programming, like taking the square root, finding
a sine or cosine, drawing a graphics shape, getting
a random number
The maker of the language (or sometimes a third
party) creates a library which contains these
actions already written for you.
Library – a group of prewritten functions and
predefined constants


You don’t have to know how to do these
things, you just know how to call the
function given in the library.
Many disciplines use special constants. The
most famous one is pi. It is convenient to
have these already defined instead of
having to look them up and type them in
yourself.
Importing a library




Before you are allowed to use library functions,
you have to import the library into your code
There are 3 different ways to do this
The simplest is just “import math” (to get the
math library)
If you use this method, you have to qualify the names of
the functions with “math.” example “math.sqrt”
Importing a library

The next way is “from math import sqrt”
(to get one specific function)

If you use this method, you can just use the
function name “sqrt”

The third way is “from math import *” (to
get all functions in the library)

Again, you do not have to qualify names if you do
this, just “sqrt”
Using the functions


After you have done the import statement, you
need to call or invoke the library functions
This is done in two ways, depending on whether
the function returns a value or does not

A function which returns a value is called as part of
another statement

A function which does not return a value is called as a
stand-alone statement
Example of using a library
function and constant
from math import sin, cos
def main():
angle = float(input(“Enter an angle in radians “))
radius = float(input(“Enter a radius”))
print(sin(angle), cos(angle))
s = sin(angle)
c = cos(angle)
area = pi * radius ** 2
Example of using a library function which does
not return a value
from graphics import *
def main():
win = GraphWin() # returns a value
win.close() # does not return a value
A few notes about libraries

Note where the import statement was placed in
the examples

It is put before and outside of the main function definition

It is better in general to be put near the top of your source
file and outside all function definitions

Why? Because that way all functions in your file can use
the library functions (it has to do with scope, which will be
discussed in chapter 5)
A few notes about libraries


Don’t include a library if you do not need to
use it – it only confuses things and reduces
the confidence of anyone reading your
code!
You do not need to import the math library
to use the math operators like +, *, -, //, %,
etc.
Testing
• Writing a program involves more than knowing
the syntax and semantics of a language
• You need to verify that your program runs
correctly, i.e. does not crash unexpectedly and
gives the correct answers/outputs.
• A simple program may be obviously right or
wrong, but once it gets past more than 10 lines, a
program needs to be tested systematically.
• Putting in some data picked at random will do a
little good, but to be confident that your program
works, you need to have a plan.
A test case
• A typical test case has four items:
• A description of the case – what are you testing for
here?
• Input data which causes the case to happen
• The expected output/outcome from that input
• The actual output/outcome from that input
• In a software company, the authors of the software would
write up test cases with the first three items, then hand
off the job to the testers.
• The testers would run the tests, record the actual outputs
and return the results to the authors, who would fix the
errors found.
A Test plan
• A test plan is a table which contains a number of
test cases.
• The quality of the test cases is more important
than the quantity.
• It is important to give test cases that do not
overlap if possible. If your program has two paths
through it and all your test cases run through just
one of the two possible paths, then you have not
thoroughly tested your program.
Python
Programming, 2/e
A test plan
• Making good test plans requires thought
and knowledge of the specifications of the
problem. Think about normal cases,
boundary cases, special cases, error cases.
Python
Programming, 2/e
Test plan for CS115
• Our test plans will only have three major columns
instead of four. The last one, the Actual Output,
is assumed to be unnecessary. If you find a case
where the expected output and the actual output
do not agree, you have found a bug and we
assume you will fix it.
• I say “major columns” because as the programs
get more complex, there may be several different
inputs for one run of the program. These would
all be under “Input” but would have their own
columns
Boundary case
• If your problem involves ranges of values
(numbers from 1 to 10, letters from C to R, etc.)
then you should be careful to test the boundary
cases. Humans commonly make the error of
going one time too far or stopping one time too
soon.
• In the case of numbers from 1 to 10 (assuming
integers), test cases should be done for 0, 1 and
2, and 9, 10, and 11.
• This is an example of checking boundary
conditions.
Error case
• Some problems have cases which will not
have correct answers or will have unusual
behaviors (crashing). These cases should
be investigated also, as far as possible.
• "non-numeric characters" will cause a
program in Python to crash if it is entered
as input when the program expects a
numeric type
Error case
"non-numeric characters" covers ALL of the
characters except the numeric digits (and
possibly "+" and "-" and "." which are all valid
parts of a number) (also "e" and "E" for
exponential numbers) so use non-numeric
characters when you mean "anything BUT
numbers"