A NEW PAGE TABLE FOR 64

Download Report

Transcript A NEW PAGE TABLE FOR 64

COSC 1306 COMPUTER SCIENCE AND PROGRAMMING

Jehan François Pâris

[email protected]

CHAPTER III PYTHON ESSENTIALS

Chapter Overview  From algorithms to programs  A few pitfalls  Installing Python  Converting Fahrenheit to Celsius  Making change  A number guessing game  Strings, Boolean expressions and I/O

Programs (I)  A computer program is a sequence of instructions that specifies the steps a computer should take while performing a certain task.

Think of explaining to a clueless math genius how to compute the average water usage of families living in detached houses inside the 610 loop

Programs (II)  A program must be understandable to 

Humans who write, debug and modify it

 Trend towards higher-level languages  Liberal use of comments 

The computer that will execute the program

 Computers take everything literally

How programming languages evolved  Move towards ease of use  Machine language  Assembly language  Higher level languages (Fortran, C, C++, …)  Scripting languages

How programming languages evolved  Move towards  Preventing or detecting some human errors  Providing tools for building bigger systems  Abstracting/hiding confusing details

Machine language  Everything inside a computer is represented as sequences of bits  0 or 1  Including instructions specifying steps to be taken by the CPU  Could write our programs in binary  Too hard

Assembly language (I)  Programmer still has to specify individual instructions but  Can use mnemonics for operation codes: 

ADD

for adding two numbers and storing results at a given address  Can replace location addresses by symbolic names  ADD tax, purchase, total

Assembly language (II)  Still micromanaging:  Must write  MPY purchase, taxrate, tax ADD tax, purchase, total  Inputs and output are especially cumbersome

High-level languages (I)  When FORTRAN came, people could write 10 20 READ 10, PURCHASE FORMAT (F8.2) TAX = PURCHASE*TAXRATE TOTAL = PURCHASE+ TAX PRINT 20, TOTAL FORMAT(F8.2)

High-level languages (II)  FORTRAN had several limitations  Poor control structures  Only simple IF branch and arithmetic FOR loop 

Will talk about these later

 Some error-prone constructs  Could only manipulate numbers  Was good at it

Higher-level languages (III)  People tried to come with better programming languages  Several failures  Languages designed by theoreticians:  ALGOL 60 and ALGOL 68  A language that wanted to be everything for everyone  PL/I from IBM

Higher-level languages (IV)  Two big successes  A language designed by programmers:  C  Later extended into C++  A "safe" language  Java

The simplest C program 

main( ) { printf("Hello world!\n"); } // main

Our programming model (I)  Applies to most programming languages  FORTRAN, C, C++, Java, C#, Ruby, Python  Program accesses constants and variables  Constants can be  Numerical values: 3, 3.0, 3.1415927

 Strings: "camel"  Many other items

Our programming model (II)  Variables specify memory addresses that contain  Numerical values  Strings  Many other items  Variables are identified by

names

Starting with a letter

Can contain numbers

There are camels and "camels"  Words starting by a letter represent variables:  maximum, total, min0, m, i, j  Words within quotes are strings  "maximum", "total", "i"  A camel has four legs and the word "camel" has five letters

Variables, numbers and strings 

alpha = 4

beta = "afternoon"

pi = 3.1416

Let's find • variables • integer numbers • floating-point numbers • strings 

this = that

Variables, numbers and strings 

alpha = 4 variable

beta = "afternoon"

pi = 3.1416

Let's find • variables • integer numbers • floating-point numbers • strings 

this = that

Variables, numbers and strings 

alpha = 4 variable

beta = "afternoon" variable

pi = 3.1416

Let's find • variables • integer numbers • floating-point numbers • strings 

this = that

Variables, numbers and strings 

alpha = 4 variable

beta = "afternoon"

variable pi = 3.1416

variable

this = that

Let's find • variables • integer numbers • floating-point numbers • strings

Variables, numbers and strings 

alpha = 4 variable

beta = "afternoon"

variable pi = 3.1416

variable

this = that variable

Let's find • variables • integer numbers • floating-point numbers • strings

Variables, numbers and strings 

alpha = 4 variable

beta = "afternoon"

variable pi = 3.1416

variable

this = that variable variable

Let's find • variables • integer numbers • floating-point numbers • strings

Variables, numbers and strings 

alpha = 4 variable integer

beta = "afternoon"

variable pi = 3.1416

variable

this = that variable variable

Let's find • variables • integer numbers • floating-point numbers • strings

Variables, numbers and strings 

alpha = 4 variable integer

beta = "afternoon"

variable pi = 3.1416

variable float

this = that variable variable

Let's find • variables • integer numbers • floating-point numbers • strings

Variables, numbers and strings 

alpha = 4 variable integer

beta = "afternoon"

variable string pi = 3.1416

variable float

this = that variable variable

Let's find • variables • integer numbers • floating-point numbers • strings

INSTALLING PYTHON (I)  Go to

python.org

 Bring mouse over

Downloads

 Second item on top bar  Click on

Python 3.4.1

 Below Download for Windows

INSTALLING PYTHON (II)  Retrieve file

python-3.4.1.msi

in your

Download

folder or your home screen  Double-click to start the installation process

A first program

print('Hello world!')

 Upper case and lower cases are not the same  "Print" is not the same as "print"  Do not forget the

quotes They must match

around 'Hello world'

Wishing a happy birthday (I)  We want to print a personalized birthday wish 

Happy birthday, Michael!

 User will enter the name of the person  Program will do the rest  Will also ask the program to prompt the user for a name 

Enter a name:

Our friend the input() function  Specific to Python  xyz = input("Blablabla:")  Will print

Blablabla:

 Will store in

xyz

the characters you will enter

The concatenation operator  The same

+

as for addition 

"U" + "H"

returns

"UH"

"How" + "are" + you" + "?"

returns

"Howareyou?"

No spaces are added!

"How _ " + "are _ " + you _ " + "?"

returns

"How are you?"

Wishing a happy birthday (II)  name = input("

Enter a name:")

print

("Happy birthday, _ " + name + "!")

Numbers and characters (I)  Consider these two assignments >>> number = 9 >>> character = '9'

Numbers and characters (II)  We now enter >>> if number == character : print('These are equal')  No output

Numbers and characters (III)  We now enter >>> if number != character : print('These are NOT equal')  Python outputs These are NOT equal

Numbers and characters (IV)  We enter >>> 5 + 3  Python outputs 8  No surprise

Numbers and characters (V)  We enter >>> "5" + "3"  Python outputs "53" 

The concatenation of string

"5"

and string

"3"

Converting Fahrenheit into Celsius  The rule is  Subtract 32 from temperature in Fahrenheit  Multiply this result by 5/9  In textbooks 

t C = (t F

- 32)  5/9

First attempt #F2C.py

# converts fahrenheit degrees into celsius degrees fahrenheit =input('Enter a temperature in degrees Fahrenheit: ') celsius = (fahrenheit - 32)*5/9 print(fahrenheit + ' degrees F equals ' + str(celsius) + ' degrees C')

Outcome  Does not work because the value we have read into the variable fahrenheit is a string 

fahrenheit – 32

is same as

'dogs' -32

Second attempt #F2C.py

# converts fahrenheit degrees into celsius degrees fahrenheit =input('Enter a temperature in degrees Fahrenheit: ') celsius = (float(fahrenheit) - 32)*5/9 print(fahrenheit + ' degrees F equals ' + str(celsius) + ' degrees C')

Outcome  Works but prints too many decimals

Third attempt #F2C.py

# converts fahrenheit degrees into celsius degrees fahrenheit =input('Enter a temperature in degrees Fahrenheit: ') celsius = (int(fahrenheit) - 32)*5//9 print(fahrenheit + ' degrees F equals ' + str(celsius) + ' degrees C') 

We use // to request an integer division

Outcome  It works but  Both variables should contain integers  We should add a

documentation string

 Starting and ending by

triple double quotes

Fourth attempt """convert fahrenheit degrees into celsius degrees """ fahrenheit =int(input('Enter a temperature in degrees Fahrenheit: ')) celsius = (fahrenheit - 32)*5//9 print(str(fahrenheit) + ' degrees F equals ' + str(celsius) + ' degrees C') input('Enter return when you are done')  We use // to specify an integer division

Outcome  Fine

Your own program  Converting acres into square yards  One acre is 4,840 square yards  Your program should prompt for the size of a property and return the number of square feet 

Enter property acreage: 2 That's 9680 square yards

Hints  You will need  One input statement  Don't forget to convert input into an integer  One computation  One output statement  Don't forget the spaces

The solution

Making change  We have a sum of money  We want to convert it into  So many twenty dollar bills  So many ten dollar bills  …  Dollars only  We will do integer arithmetic

How to proceed  We do integer arithmetic    r r Amount = 20  n 20 20 = 10  n 10 + r 10 10 = 5  n 5 + r 5 + r 20  n 1 = r 5

Steps (I)  >>> amount = 57  >>> ntwentys = amount // 20  >>> print(str(ntwentys))  2  >>> rtwentys = amount % 20  >>> print(str(rtwentys))  17

Steps (II)  >>> amount = 57  >>> ntens = rtwentys // 10  >>> print(str(ntens))  1  >>> rtens = rtwentys % 10  >>> print(str(rtens))  7

A new operator  Remainder  %  4%1 is 1  16 % 4 is 0  100 % 11 is 1

The solution (I) # givechange.py

""" This program prompts repeatedly for a value in dollars and converts it into its equivalents in twenty, ten, five and one dollar bills. The program terminates when the user enters a zero value """

The solution (II) amount = int(input("Enter an integer amount of dollars: ")) while amount != 0 : n20 = amount // 20 remainder20 = amount % 20 n10 = remainder20 // 10 remainder10 = remainder20 % 10 n5 = remainder10 // 5 n1 = remainder10 % 5

The solution (III) print('$' + str(amount) + ' is same as ' + str(n20) + ' $20 bill(s) ' + str(n10) + ' $10 bil(s) ' + str(nfives) + ' $5 bill(s) and ' + str(nones) + ' $1 bill(s).') amount = int(input("Enter an integer amount of dollars: ")) print('Goodbye!')

One more example  Comporting the cost of prix-fixe dinner  A well-of UH graduate wants to invite some of her friends to a prix-fixe dinner where beverages, but not tips, are included.

 She wants to know how much it would cost

What she wants  Something like:  Enter the price of meal: 65 Enter the number of guests: 4 Enter the tipping rate (in percent): 20 Your total cost will be $312.00

Algorithm (I)

Input: nguests,price, tiprate Compute meal cost Output: meal cost

Algorithm (II)  How to compute the meal cost?

total_price =

Algorithm (II)  How to compute the meal cost?

total_price = price*nguests tip = …

Algorithm (II)  How to compute the meal cost?

total_price = price*nguests tip = total_price*tiprate/100 cost = …

Algorithm (II)  How to compute the meal cost?

total_price = price*nguests tip = total_price*tiprate/100 cost =total_price + tip

Algorithm (II)  How to compute the meal cost?

total_price = price*nguests tip = total_price*tiprate/100 cost =total_price + tip OR

cost = price*nguests*(1 + tiprate/100)

The program (I)  Insert template:

"""Jehan-Francois Paris Computing the cost of a meal COSC 1306 Fall 2014 This program … """

The program (I)  Add the three input statements

price = float(input(…)) nguests = float(…)) tiprate = float(…) In the specified order and with the specified prompts

The program (II)  Add the body

total_price = price*nguests tip = total_price*tiprate/100 cost =total_price + tip In the right order

The program (III)  Add the output statement

POOR: print("Your total cost will be $" + str(cost)) BETTER: print("Your total cost will be $%.2f " % cost) With the specified text

Check for  Matching quotes  IDLE puts them in green  Matching parentheses  Order of computation steps  MUST compute t

otal_price

adding them up and

tip

BEFORE  MUST have input computing

tip tip_rate

BEFORE

Number guessing game  We use a random number generator to generate a random number between 1 and 10  Users are asked to guess the number until they come with the right value

Number guessing game  We use a random number generator to generate a random number between 1 and 10  Users are asked to guess the number until they come with the right value

Flow chart

Generate RN n Input i False i == n True You win

More about flow charts  Graphic representation of flow of control  Loops represented by loops  Ifs have two branches

False ???

True

Simple if  If condition : something  If tank_empty : get_gas

condition False True something

If with else clause (I)

False condition True

 If condition: something else: other stuff

other stuff something

If with else clause (II)  If hungry : Macdonald else : Starbucks  In either case, you will leave the freeway

While  while condition : something

condition True

False

while stain : keep_washing

something Go back!

How to generate RN  Import a function from module random 

from random import randint

randint(min, max)

 generates an integer between min and max

The program (I)  # guess.py

""" must guess a random number between 1 and 10 """ # secret # guess

The program (II)  from random import randint secret = randint (1,10) guess = -1

# bad guess

while guess != secret : guess = int(input("Enter your guess: ") print("You win!")

A better program  Tells whether guess is too low or too high  Must consider three cases inside the loop  Correct guess  Guess that is too low  Guess that is too high

The better program (I)  # guess.py

""" must guess a random number between 1 and 10 """ # secret is number to guess # guess is user’s guess from random import randint secret = randint (1,10) guess = -1

# bad guess

The program (II)  while guess != secret : guess = int(input("Enter your guess: ")) if guess == secret : print ("You win!") else : if guess < secret : print ("Too low!") else : # we know guess > secret print ("Too high!")

Using an elif (I)  Too many nested ifs

if cond-1 : … else if cond-2 : … else if cond-3 : … else …

Example while guess != secret : guess = int(input("Enter your guess: ")) if guess == secret : print ("You win!") elif guess < secret : # observe indentation print ("Too low!") else: print ("Too high!")

Using an elif (II)  With elif, lines align better

if cond-1 : … elif cond-2 : … elif cond-3 : … else …

Indenting advice  Python attaches great importance to indenting  You cannot indent anything that is not inside  An if, a while, a for, …  A function declaration or a main function  Your indentation must be consistent  Do not mix spaces and tabs

Floating point values  Three main differences  Cannot handle

extremely large

or

extremely small values

Limited precision

 Can manipulate trillions of dollars but results are not exact to the cent  Must specify number of decimals

Limited precision # precision.py

""" floating-point computations can be inaccurate """ biggie = 5E9 delta = 5E-9 beta = biggie + delta gamma = beta - biggie print ('delta = ' + str(delta) + ' but gamma = ' + str(gamma))

The output

delta = 5e-9 but gamma = 0.0

Why?

 Computations are carried out with a limited number of significant bits  Result has a limited number of significant digits  Be careful when computing very small differences between two numbers

Note  Limitations on floating point number size and precision are 

Hardware dependent

Shared

by most programming languages  Unlike Python, most programming languages do not support arbitrary-size integers  Python is

better

Displaying floating point numbers  Easiest way to specify number of decimal places is

string interpolation

'Answer is %.nf ' %x

does two things  It inserts the value of x inside the string  It specifies that the string representation of x should have n decimal places

Example (I)  pi = 3.1415917

print('pi equals %.1f' % pi ) print('pi equals %.2f' % pi ) print('pi equals %.3f' % pi ) print('pi equals %.4f' % pi )

Example (II)  Program prints pi equals 3.1

pi equals 3.14

pi equals 3.142

pi equals 3.1416

 Values are nicely rounded

Converting o F into o C revisited (I) #F2CF.py

"""converts fahrenheit degrees into celsius degrees """ fahrenheit =float(input('Enter a temperature in degrees Fahrenheit: ')) celsius = (fahrenheit - 32)*5/9 print('%.1f degrees F equals %.1f degrees C' %(fahrenheit, celsius))

Converting o F into o C revisited (II)  Output is

Enter a temperature in degrees Fahrenheit: 100 100.0 degrees F equals 37.8 degrees C

More about string interpolation  Can interpolate  Floating-point numbers in

scientific notation

>>> c = 300000 >>> print('c = %.3e km/s'% c) c = 3.000e+05 km/s

Integers using %d

Strings using %s

Example (I)  # interpolate.py

""" silly demo """ name = input("What's your name?") nclasses=int(input('How many classes are you taking? ')) print ('%s is taking %d classe(s)' %(name, nclasses))

Example (II)  Output is:

What's your name? Bill How many classes are you taking? 5 Bill is taking 5 classe(s)

Using the proper quotes  We had to use double quotes (") in

name = input("What's your name?")

because the string contained an apostrophe (')  we could have "escaped" the apostrophe as in

name = input('What\'s your name?')

More escapes  Escape sequence

\'

\"

\\ \n \r

Meaning Apostrophe Double quote Backslash Newline Carriage return

Escaping the percent sign  Not required in normal strings

>>> print("Use the %.3f format") Use the %.3f format

 Required when we use string interpolation

>>> print("Use %%.3f to print %.3f" % 3.1416) Use %.3f to print 3.142

Boolean type  Two values:  True and False  Created as  Result of a comparison:

==, !=, >, >=, <, <=

 Conversion using

bool

(…)

function 

Zero values

into a False and

anything empty

converts  Anything else converts into a

True value

Examples

>>> a = 3 >>> b = 5 >>> p = (a < b) >>> q = (b <= a) >>> print("p = " + str(p) + " and q = " +str(q)) p = True and q = False

Boolean operations (I) 

AND:

 True if both operands are true

a F F T T b F T F T a and b F F F T

This is called a truth table

Boolean operations (II) 

OR:

 True unless both operands are false

a F F T T b F T F T a or b F T T T

Boolean operations (III) 

NOT:

 True if operand is false

a not a F T T F

Boolean operations (IV) 

Equality/Mutual Implication:

 True when both operands are equal  Represented by a == sign

a F F T T b F T F T a

==

b T F F T

Boolean operations (V) 

Inequality/Exclusive OR (XOR):

 True when operands are not equal  Represented by a != sign

a F F T T b a

!=

b F T F T F T T F

Notes  XOR is used for  Generating parity bits  Hardware hashing

Examples  Assuming P is True and q is False

>>> p or q True >>> p and q False >>> not p False >>> p != q True

Variables and objects  Variables point to objects  Integers  Strings  Floating-point numbers

What is an object?

 Short for

data object

Example:

dates  Cannot add two dates but can compute their difference  Can initialize date  Can compute weekday(date)  Special date today()  Multiple ways to convert a date into a string

What we need to remember  Not all operations are valid on all data  Cannot add dates  Cannot compute the square root of a string  …  These things should be made impossible  We will see later in the semester how to define

objects

for specific kinds of data  Dates  Health records  ….

String methods 

These methods never modify the string they apply to!

 See pages 90 to 95 of text 

Do not memorize them (yet) please!

An example

s.capitalize():

capitalizes the first letter of the string and converts all other letters to lower case

Examples (I) >>> a = 'bill' >>> a.capitalize() 'Bill' >>> b = 'Bill' >>> b.capitalize() 'Bill'

Examples (II) >>> c = 'bILL' >>> c.capitalize() 'Bill' >>> d ='Billy Bob' >>> d.capitalize() 'Billy bob'

Better but not perfect 

s.title():

capitalizes the first letter of each word in the string and converts all other letters to lower case as in the title case  Defines words in a very crude fashion

Examples (I) >>> s = 'biLLy Bob' >>> s.title() 'Billy Bob' >>> s ='jehan-francois' >>> s.title() 'Jehan-Francois' >>> s.title()

Examples >>> s = "dean's list" >>> s.title() "Dean'S List" >>> s "dean's list" >>>

Dollars into bills revisited (I)

# dollars2bills.py

""" This program prompts repeatedly for a value in dollars and converts it into its equivalents in twenty, ten, five and one dollar bills. It terminates when the user enters a zero value """

Dollars into bills revisited (II)

# amount is the dollar amount we enter # ntwentys is number of $20 bills we need # ntens is number of $10 bills we need # nfives is number of $5 bills we need # nones is number of $1 bills we need # outstr is our output string

Dollars into bills revisited (III)

amount = int(input("Enter an integer amount of dollars: ")) while amount != 0 : outstr = '$' + str(amount) + ' is same as ' ntwentys = amount // 20 if ntwentys != 0 : outstr = outstr + str(ntwentys) + ' $20 bill(s) ' temp = amount % 20 ntens = temp // 10 if ntens != 0 : outstr = outstr + 'and ' + str(ntens) + ' $10 bill(s) '

Dollars into bills revisited (IV)

temp = temp % 10 nfives = temp // 5 if nfives != 0 : outstr = outstr + 'and ' + str(nfives) + ' $5 bill(s) ' nones = temp % 5 if nones != 0 : outstr = outstr + 'and ' + str(nones) + ' $1 bill(s) ' outstr.replace('as and', 'as') print(outstr) amount = int(input("Enter an integer amount of dollars: ")) print('Goodbye!')

Outputs Enter an integer amount of dollars: 20 $20 is same as 1 $20 bill(s) Enter an integer amount of dollars: 7 $7 is same as 1 $5 bill(s) and 2 $1 bill(s) Enter an integer amount of dollars: 35 $35 is same as 1 $20 bill(s) and 1 $10 bill(s) and 1 $5 bill(s) Enter an integer amount of dollars: 0 Goodbye!

Useful shorthand  Can replace    a = a + … by a += … b = b – … by b –= … c = c * … by c *= …  Cannot use i++, i --, ++i , --i constructs of C  ++i read as +(+i) = i  --i read as –(–i) •

Does not work!

Examples (I) >>> i=1 >>> i += 1 >>> print(i) 2 >>> i++ SyntaxError: invalid syntax >>> ++i 2

Examples (II)  In the preceding program we could have written

… outstr += str(ntwentys) + ' $20 bill(s) ' outstr += 'and ' + str(ntens) + ' $10 bill(s) ' … outstr += 'and ' + str(nfives) + ' $5 bill(s) ' … outstr += and ' + str(nones) + ' $1 bill(s) '

Operator precedence (I)  Recall the rules of precedence of arithmetic and algebra  From highest to lowest  Exponentiation (**)  Unary + and –  Multiplication, divisions and remainder (*, / ,//, %)  Addition and subtraction (+ and -)

Operator precedence (II)  Python extends these rules to other operators  From

highest

 Boolean

not

to

lowest

 All arithmetic operations  All comparison operators (==, !=, <, …)  Boolean

and

(like multiplication)  Boolean

or

(like addition)

Examples 

x**2*2 + 4*x

is same as

((x**2)*2) +( 4*x)

(x + 3)/4 + 2

is same as (

(x + 3)/4) + 2

Examples  Allows us to write

if a < b and c < d :

for

if (a < b) and (c < d ):

 Allows us to write

a and b or not c

for (

a and b ) or (not c)

A common sense rule  Some expressions such as a*x**2 + b*x + c do not need parentheses  Nobody has ever been fired for writing

if (a < b) and (c < d ):

or even (

a and b ) or (not c)

It is always better to play safe!

How our programs are translated  Our programs are not written in machine language  Cannot be directly executed by any computer  Must be first translated  Two approaches  Compiled languages  Interpreted languages

Compiled languages (I)  Programs written in Fortran, C, C++ and so on go to a program that translates them into directly executable code  The

compiler

 Doing

gcc myprogram.c –o myprogram

produces an executable file called that can run anytime

myprogram

Compiled languages (II)

C program C compiler Executable

Advantages  The executable can run on any computer with  Same CPU instruction set  Same —or compatible—operating system  We can sell copies of the executable without revealing the secrets of our program  Reverse engineering is possible but very time-consuming

Intellectual Property Issues (I)  Law protects programs in two ways  They can be

trade secrets

 Protection ends once secret is revealed.

 The can be

copyrighted

 Only protects

expressions

of an idea  Others can write a program doing the same things are your program using different instructions

Intellectual Property Issues (II)  Selling C programs or Python programs is a very risky proposition  Invites imitators  Best solution is  Selling

copies of executables

 Properly obfuscated  Keeping

source code secret

Interpreted languages (I)  Languages like Basic, Perl, Python and Ruby are not compiled  Translated into bytecode before being executed  Bytecode is interpreted by the language interpreter

Interpreted languages (II)

Python Program Byte code Python Interpreter:

translates program into bytecode then executes it

Advantages 

Platform independence:

 Bytecode can run on any platform for which there is an interpreter 

Dynamic typing:

 Same variable can refer to a string then an integer then … 

Smaller executable sizes

Disadvantages 

Portability limitations :

 Bytecode will not run run on any machine on which the interpreter was not installed.

Speed:

 Bytecode is not optimized for a specific architecture  Just-in-time compilation introduces delays  Cannot sell a copies of a program without

revealing its source code

A partial solution  In many cases, speed is not an issue outside of loops than get executed thousand and thousands of times  Loops inside other loops  Can

rewrite

code for these

inner loops

in C and include this code into a Python program 

Use Python C API

Neither fish nor fowl  Java is compiled  Like Fortran, C, … into bytecode  Like Perl and Python  Bytecode is executed by

Java Virtual Machine