MIME-Version: 1.0 Content-Location: file:///C:/F48430D2/Week2.htm Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset="us-ascii" Week 2

Week 2

Numbers and Strings

Indiana U= niversity

Com= puter Science A202 / A598

and Informatics I211

 

Review: modules

<= ![if !supportLists]>n   Python mod= ules (including your programs) should never do I/O when loading

<= ![if !supportLists]>q   exception: an application after executing a main() call in its last line

<= ![if !supportLists]>n   Program structure for this course

<documentation string, beginning with assignment name, lab section, and team member names and usernames>

<various statements, comments, and blank lines>

def main():
<main body statements, comments, and blank lines>

main()

 

 

Review: indentation

<= ![if !supportLists]>n   In Python (unlike most languages), indentation helps determines the meaning of the program, so be careful with indentation

<= ![if !supportLists]>n   Don’t forget the colon punctuation that indicates one or more following lines wil= l be indented, for example in function definitions

<= ![if !supportLists]>n   On paper, = if indentation is messed up, indicate what it should be, as in this example:

def main():

   = ; print ‘Nice line’

  pr= int ‘Line with bad indentation’
print ‘Another properly indented line’

 

 

This week’s success strategies

<= ![if !supportLists]>n   Keep up wi= th the reading

<= ![if !supportLists]>q   new reading assignment for thi= s is week posted on the web

<= ![if !supportLists]>q   read assigned material at leas= t once before lab

<= ![if !supportLists]>q   reading more than once, and re= ading before lectures, is strongly recommended

<= ![if !supportLists]>q   study the section of Appendix = A associated with each assigned chapter

<= ![if !supportLists]>q   do the true/false and multiple choice exercises and check your answers with the key on the web (after this Wednesday)

<= ![if !supportLists]>q   consider the discussion questi= ons

<= ![if !supportLists]>q   it is excellent practice to do= as many programming exercises as you can, even if they are not assigned

<= ![if !supportLists]>q   in many cases the answers to discussion questions and programming exercises can be tested easily by tryi= ng things in the IDLE

Quizzes

<= ![if !supportLists]>n   Expect a q= uiz next week

<= ![if !supportLists]>n   You are responsible for both assigned readings and class material from the start of= the course through the preceding week

<= ![if !supportLists]>n   In particu= lar, you are responsible for details of Python in Appendix A (associated with assigned reading)

<= ![if !supportLists]>q   except for keywords of syntax = not in assigned reading

<= ![if !supportLists]>n   Quizzes are closed book. You will be given names of library functions that are needed f= or a quiz, but not descriptions of them if they are in Appendix A

 

This week

<= ![if !supportLists]>n   All about = Python numbers, plus

<= ![if !supportLists]>q   operator precedence and associativity

<= ![if !supportLists]>q   review of some basic computer = math

<= ![if !supportLists]>q   encoding and powers of two

<= ![if !supportLists]>n   Introducti= on to Python strings, plus

<= ![if !supportLists]>q   character encoding<= /span>

<= ![if !supportLists]>q   working with sequences

<= ![if !supportLists]>n   A bit more= on Python importing and built-in functions

<= ![if !supportLists]>n   Lots that’s used in other programming languages and many non-programming contexts

 

 

Digression on importing

<= ![if !supportLists]>n   The imp= ort statement loads one or more modules and binds them to corresponding variable names

<= ![if !supportLists]>q   syntax: import <modu= le name>, … , <module name>

<= ![if !supportLists]>n   Module references refer to elements of a module

<= ![if !supportLists]>q   syntax: <module name> . <name of module variable>
>>> im= port math, string

>>> math

<module 'math' (built-in)>=

>>> math.sqrt(4)

2.0

Digression continued: from statement

<= ![if !supportLists]>n   The fro= m statement loads a module and binds one or more variables to the values of corresponding variables in the module

<= ![if !supportLists]>q   syntax: from <module name> import <variable>,…,<variable>=

<= ![if !supportLists]>q&nb= sp;  alternate syntax: from <module name> import *

>>> from math import sqrt

>>> sqrt(4)

2.0

>>> from math import *<= /b>

>>> pi

3.1415926535897931

Built-in functions

<= ![if !supportLists]>n   Built-i= n values do not have to be imported

<= ![if !supportLists]>q   as if every Python program (mo= dule) begins with

from __builtin__ import *

<= ![if !supportLists]>q   similar to the java.lang packa= ge in Java

<= ![if !supportLists]>q&nb= sp;  the built-in values (all functions) we have seen so far are float, input, and range

<= ![if !supportLists]>n   The name o= f a function is actually the name of the variable it is stored in

<= ![if !supportLists]>n   All variab= les (including functions) that are not built-in must be imported or defined bef= ore they are referred to

 

Numeric data types

<= ![if !supportLists]>q   There are three numeric data t= ypes in Python

<= ![if !supportLists]>n     int – integers

<= ![if !supportLists]>q    whole numbers that aren’t= too big

<= ![if !supportLists]>n     float – floating point numbers=

<= ![if !supportLists]>q    numbers with a decimal point, w= hich can “float” over several hundred positions

<= ![if !supportLists]>q    values are only approximate, e.= g. 1.0 / 5 / 5 is not quite 0.04 (1/25)

<= ![if !supportLists]>q    represented internally in a bas= e-2 “scientific notation”, with a mantissa and exponent<= /span>

<= ![if !supportLists]>n     long – “big” inte= gers

<= ![if !supportLists]>q    much less efficient for computa= tion than the int type

<= ![if !supportLists]>q   Most programming languages distinguish between integers and floating point numbers

<= ![if !supportLists]>n     some, like Java, have multiple = sizes of both integers and floats

<= ![if !supportLists]>n     most do not have the equivalent= of Python’s long type

 

Numeric literals

<= ![if !supportLists]>n   Numeric li= terals are how numbers are represented ‘literally’ in programs and data input

<= ![if !supportLists]>n   (view shell transcript)

<= ![if !supportLists]>n   Each type = has its own “literal” form (how elements of the type are represente= d in programs and input)

<= ![if !supportLists]>q   ints are just digits, perhaps = with + or – sign

<= ![if !supportLists]>q   longs are ints with an “L” (or “l”) suffix

<= ![if !supportLists]>q   floats have a decimal point an= d may be in “scientific notation” with an “e” followed by= a signed exponent (base 10)

<= ![if !supportLists]>n   Printed and literal representations may differ

Some built-in numeric functions

<= ![if !supportLists]>n   (transcrip= t)

<= ![if !supportLists]>n   The functi= on type can be used to determine the type of a number (or any Python value)

<= ![if !supportLists]>n   int, fl= oat, and long convert numbers (and strings) = to their respective type

<= ![if !supportLists]>q   int will return a long if necessa= ry

<= ![if !supportLists]>n   abs returns the “absolute value” of a n= umber

<= ![if !supportLists]>q   negates its argument if necess= ary so a positive value is always returned

<= ![if !supportLists]>n   max and min take two or more numeric arguments and return the one with the greatest and least value, respectively.

 

Integer operators

<= ![if !supportLists]>n   (transcrip= t)

<= ![if !supportLists]>n   The usual = +, -, *, and / operators

<= ![if !supportLists]>n   Operators = given only integers always return integers

<= ![if !supportLists]>n   / returns the quotient of integer division<= /o:p>

<= ![if !supportLists]>q   think of it as “gozinta reversed”: 7 / 2 is 3 since 2 “gozinta” 7 3 times

<= ![if !supportLists]>n   % returns the remainder of integer division<= /o:p>

<= ![if !supportLists]>q   sometimes called the “modulus” or “mod” operator

<= ![if !supportLists]>q   handy for finding what’s= left over, and for going in circles

<= ![if !supportLists]>n   ** is exponentiation

<= ![if !supportLists]>q&nb= sp;  a ** b is a raised to the power b (a multiplied by itself b-1 times)

Operator precedence and associativity<= /p>

<= ![if !supportLists]>n     Traditional rules to resolve ambiguity in expressions

<= ![if !supportLists]>n     Precedence: which operations ha= ve priority?

<= ![if !supportLists]>q    for example 3 * 2 ** 4 m= eans 3 * (2 ** 4) =3D 3 * (2 * 2 * 2 * 2) =3D 48,

    =   not (3 * 2) ** 4 =3D 6 ** 4 =3D 6 * 6 * 6 * 6 =3D 1296

<= ![if !supportLists]>q    in general operators on the sam= e line below are of equal priority, lines are in order of decreasing priority=

**

* / %

+ -

<= ![if !supportLists]>n     Associativity: which order for operators of the same priority?

<= ![if !supportLists]>q    for example 8 / 4 / 2 me= ans (8 / 4) / 2 =3D 1,
not 8 / (4 / 2) =3D 8 / 2 =3D 4

<= ![if !supportLists]>q    all Python operators associate = left to right

<= ![if !supportLists]>n     Any expression may be enclosed = in parenthesis, have the highest precedence

<= ![if !supportLists]>q     for example (3 * 2) ** 4 is = 1296 and 8 / (4 / 2) is 4

<= ![if !supportLists]>n     What is the value of 2 ** 3+= 1 / 2 * 2 - 1 ?

<= ![if !supportLists]>n     Answer: 7

Binary encoding

<= ![if !supportLists]>n   1 bit can represent (any!) two possibilities

<= ![if !supportLists]>n   2 bits can represent 2**2 =3D 4 possibilities

<= ![if !supportLists]>q   binary representation of 0 to = 3, or represent 4 colors

0 =3D 00        =      |  black =3D 00

1 =3D 01        =      |  white =3D 01

2 =3D 10        =      |  red   =3D 10=

3 =3D 11        =      |  blue  =3D 11

<= ![if !supportLists]>n   3 bits can represent 2**3 =3D 8 possibilities

<= ![if !supportLists]>q   binary representation of 0 to = 7, or -4 to 3 (3 bit signed integer)

0 =3D 000   4 =3D 100  |=   -4 =3D 111   0 =3D= 000

1 =3D 001   5 =3D 101  |=   -3 =3D 110   1 =3D= 001

2 =3D 010   6 =3D 110  |=   -2 =3D 101   2 =3D= 010

3 =3D 011   7 =3D 111  |=   -1 =3D 100   3 =3D= 011

<= ![if !supportLists]>n   n bits can represent 2**n possibilities

 

Powers of two

<= ![if !supportLists]>n   2**8 =3D 2= 56

<= ![if !supportLists]>q   8 bits =3D 1 byte can represen= t 256 possibilities

<= ![if !supportLists]>n   2**10 =3D = 1024 =3D 1 K (kilo), a bit over a thousand

<= ![if !supportLists]>n   2**20 =3D = 1024 * 1 K =3D 1 M (meg), over a million

<= ![if !supportLists]>q   2**20 =3D 2**(10+10) =3D 2**10= * 2**10 =3D 1024 * 1024

<= ![if !supportLists]>n   2**30 =3D = 1024 * 1 M =3D 1 G (gig), over a billion (10**9)

<= ![if !supportLists]>n   2**32 =3D = 2**2 * 2**30 =3D 4 G

<= ![if !supportLists]>q   desktop computers generally ha= ndle integers (including memory addresses) in 32 bit chunks

<= ![if !supportLists]>n   2**40 =3D = 1024 * 1 G =3D 1 T (tera), over a trillion (10**12)

<= ![if !supportLists]>n   2**50 =3D = 1024 * 1 T =3D 1 P (peta), over a million billion

 

Exercise

<= ![if !supportLists]>n    Write an application that prom= pts for a number of rows and prints and a table with row n containing n, n**2, = and 2**n

Enter number of rows: 10=

1 1 2

2 4 4

3 9 8

4 16 16

5 25 32

6 36 64

7 49 128

8 64 256

9 81 512

10 100 1024

<= ![if !supportLists]>q   soon we’ll learn how to m= ake nice columns

<= ![if !supportLists]>n&nb= sp;   Answer: = growth.py

Floating point operations

<= ![if !supportLists]>n   (transcrip= t)

<= ![if !supportLists]>n   Same opera= tions as integers, but the result is a float

<= ![if !supportLists]>q&nb= sp;  / is r= eal division, not the quotient

<= ![if !supportLists]>q   in a mixed-type operation with= a float and an integer, the integer is first converted to a float<= /span>

<= ![if !supportLists]>n   Converting floats to integers

<= ![if !supportLists]>q   int returns the whole part

<= ![if !supportLists]>q   round returns the whole part of the nearest integer

<= ![if !supportLists]>n   Lots more functions in the math library module, such as

<= ![if !supportLists]>q   sqrt for square roots

<= ![if !supportLists]>q   log for logarithms

<= ![if !supportLists]>q&nb= sp;  sin, e= tc. for trigonometry

 

How big and small can Python numbers get?

<= ![if !supportLists]>n   (transcrip= t)

<= ![if !supportLists]>n   ints are s= tored in 32 bits

<= ![if !supportLists]>q   1 bit is used for the sign (pl= us or minus)

<= ![if !supportLists]>q   ints range from – 2**31 = to 2**31 – 1

<= ![if !supportLists]>n     since 0 is represented as a pos= itive number

<= ![if !supportLists]>n   longs may = be of practically unlimited size

<= ![if !supportLists]>q   but long operations can take practically unlimited amounts of time

<= ![if !supportLists]>n   floats can= be very big or very small

<= ![if !supportLists]>q   never have more than about 17 = digits of precision

<= ![if !supportLists]>q   after a lot of computation the number of meaningful digits may be much less than 17

<= ![if !supportLists]>q   stored in 64 bits containing b= ase 2 mantissa and exponent

 

Introduction to Python strings

<= ![if !supportLists]>n   We’ll learn about

<= ![if !supportLists]>q   string literal representations=

<= ![if !supportLists]>q   character codes

<= ![if !supportLists]>q   basic string operations

<= ![if !supportLists]>q   basic sequence operations=

Python string literals

<= ![if !supportLists]>n    (transcript)=

<= ![if !supportLists]>n    One-line strings begin and end= with matching single- or double-quote characters

<= ![if !supportLists]>q   if a line ends with a \ charact= er, the following line is treated as if it were at the end of the line above (anytime in Python, not just strings)

<= ![if !supportLists]>n    Multiline strings begin and en= d with three single-quote characters

<= ![if !supportLists]>n&nb= sp;   Backslash \ is the string escape character

<= ![if !supportLists]>q   combined with one or more follo= wing characters, it may represent a special character

<= ![if !supportLists]>q   \n, \r, and \t represent newline, retu= rn, and tab characters, respectively

<= ![if !supportLists]>q&nb= sp;  see documentation for string literal for other possibilities

<= ![if !supportLists]>n    Raw string literals start with= r

<= ![if !supportLists]>q&nb= sp;  r’\a\b’ is the same as ‘\\a\\b’

<= ![if !supportLists]>q   very handy for regular expressi= ons later in the course

 

Popular 7 and 8 bit character codes

<= ![if !supportLists]>n   ASCII code is the much used old character code<= /o:p>

<= ![if !supportLists]>q   American Standard Code for In= formation Interchange

<= ![if !supportLists]>q   7 bits, representing 2**7 =3D = 128 characters

<= ![if !supportLists]>q   control codes on standard keyb= oards for all ASCII characters

<= ![if !supportLists]>q   see http://www.asciitable.com/

<= ![if !supportLists]>n   ASCII may = be expanded one bit for another 128 characters (256 total)

<= ![if !supportLists]>q   extended ASCII character sets with graphic characters

<= ![if !supportLists]>q   Latin1, or ISO 8859-1, set has characters for European languages

<= ![if !supportLists]>n     for example, in the 5th line of the www.iub.edu source

<= ![if !supportLists]>n     see http://w= ww.htmlhelp.com/reference/charset/iso160-191.html

 

 

Unicode

<= ![if !supportLists]>n   ISO (International Standards Organization) Unicode

<= ![if !supportLists]>q   used in most modern computer s= ystems

<= ![if !supportLists]>q   16 bit characters, provide 2**= 16 =3D 64 K =3D 65,536 possibilities

<= ![if !supportLists]>q   also a 32 bit version, with 2*= *32 =3D 2**(2 + 30) =3D 2**2 * 2**30
=3D 4 Gig =3D over 4 billion possibilities

<= ![if !supportLists]>q   includes almost all the charac= ters in all the written languages of the world

<= ![if !supportLists]>n   Python has= a Unicode string type

<= ![if !supportLists]>q   a sequence of 16 bit character= s

<= ![if !supportLists]>q   similar to the string type, wi= th a few differences

<= ![if !supportLists]>q&nb= sp;  Unicode literals are like string literals, but preceded by u

<= ![if !supportLists]>q   good to know about, but not us= ed in this course

 

Python strings

<= ![if !supportLists]>n    Python strings are sequence= s of 8 bit characters

<= ![if !supportLists]>q   ANSII characters plus escaped n= umeric codes for the second 128 possibilities

<= ![if !supportLists]>q   string size is limited only by available memory

<= ![if !supportLists]>n    There are three types of Python sequences: strings, lists, and tuples

<= ![if !supportLists]>q   we’ve seen range lists, a= nd will see more of lists and tuples soon

<= ![if !supportLists]>n    Characters are represented as strings containing one character

<= ![if !supportLists]>q   frequently in other languages, = like Java, characters have their own type

<= ![if !supportLists]>n    Strings are immutable

<= ![if !supportLists]>q   they cannot be mutated (modifie= d) in any way

<= ![if !supportLists]>q   but new strings can replace oth= er strings as variable values

>>> s =3D 'a‘=

>>> s

'a'

>>> s =3D s + 'b'

>>> s

'ab'

Sequence operators

<= ![if !supportLists]>n    The + operator concaten= ates two sequences

<= ![if !supportLists]>q   both sequences must be of the s= ame type

<= ![if !supportLists]>q   a sequence is returned containi= ng the elements of the first sequence followed by those of the second

<= ![if !supportLists]>q   the concatenated sequences are = not changed

<= ![if !supportLists]>n    The repetition operator * takes a sequence s and an integer n and returns a sequence containing the elements of s repeated n times

<= ![if !supportLists]>q&nb= sp;  s conca= tenated with itself n-1 times (when n is positive)<= /span>

>>> 'ab' * 3

'ababab'

>>> 'ab' * 0

''

>>> ' ' * 50

'        =             &nb= sp;            =             &nb= sp;    '

>>> len(_) # the variable _ contains the value of the last expression

50

Some built-in string functions

<= ![if !supportLists]>n   (transcrip= t)

<= ![if !supportLists]>n   Some built= -in string functions

<= ![if !supportLists]>q   ord takes a character and returns = its “ordinal”, or corresponding integer, which for ASCII character = is its position in the ASCII code

<= ![if !supportLists]>q   chr does the reverse, converting = an integer to a character

<= ![if !supportLists]>q   len returns the length of a strin= g

<= ![if !supportLists]>n     it actually returns the length = of any sequence

<= ![if !supportLists]>q   eval takes a string and returns the result of evaluating it as an expression

 

String input

<= ![if !supportLists]>n   (transcrip= t)

<= ![if !supportLists]>n   The inp= ut function evaluates as an expression the line typed by the user

<= ![if !supportLists]>q   this is what you want for nume= ric input

<= ![if !supportLists]>q   this is not right if what you = want is just the characters the user input

<= ![if !supportLists]>n   The built-= in raw_input function is like input, but does not do evaluation=

<= ![if !supportLists]>n   Could defi= ne input using raw_input

def input(prompt):

  &nbs= p; return eval(raw_input(prompt))

Sequence indexing

<= ![if !supportLists]>n    (transcript)=

<= ![if !supportLists]>n&nb= sp;   The elements of a sequence s are indexed (numbered) 0 through len(s)-1<= /o:p>

<= ![if !supportLists]>n    A sequence element reference r= eturns the indicated element of a sequence

<= ![if !supportLists]>q&nb= sp;  syntax: <sequence expression> [ <index expression> ]

<= ![if !supportLists]>q   same as array indexing in most languages, including Java

<= ![if !supportLists]>n    A slice reference retur= ns a subsequence given indices of the first and last+1 elements

<= ![if !supportLists]>q&nb= sp;  syntax: <sequence exp> [ <first index exp> : <last+1 i= ndex exp> ]

<= ![if !supportLists]>q   the first and last index expres= sions are optional and default to the beginning and end of the sequence, respecti= vely

<= ![if !supportLists]>q   if the last index is negative, = it counts backwards from the end

<= ![if !supportLists]>q   similar to Java’s subs= tring method

Sequence iteration

<= ![if !supportLists]>n   The for= statement iterates, in order, over the elements of a sequence

<= ![if !supportLists]>q   syntax: for <variabl= e> in <sequence expression> : <body>

>>> for char in 'abcdefg':

        print char, ord(char)

 &nbs= p;

a 97

b 98

c 99

d 100

e 101

f 102

g 103

>>>

Some functions in module string

<= ![if !supportLists]>n    (transcript)=

<= ![if !supportLists]>n    upper(s) and lower(s) convert le= tters in string s to upper and lower case

<= ![if !supportLists]>n    center(s, n), ljust(s, n), and rjust(s, n) return a string of length n containing s with spaces added so that = s is centered, left, or right justified, respectively

<= ![if !supportLists]>n    find(s, sub) and rfind(s, sub) retur= n the index of the beginning of the first and last occurrence of substring sub= in s, respectively

<= ![if !supportLists]>n    strip(s), lstrip(s), and rstrip(s) remove whitespace from both ends of s, or just the left or right ends, resp= .

<= ![if !supportLists]>q   whitespace is space, newline, r= eturn, and tab characters

<= ![if !supportLists]>n&nb= sp;   replace(s, old, new) returns a copy of s with all occurrences of substring old= replaced by new

<= ![if !supportLists]>n    See the string module document= ation for many more useful functions

String formatting

<= ![if !supportLists]>n   (transcrip= t)

<= ![if !supportLists]>n   Convenient formatting of floating-point numbers and left and right justification in a space of given width

<= ![if !supportLists]>n   % is the formatting operator

<= ![if !supportLists]>q&nb= sp;  syntax: <format string> % ( <value> , ,= <value> )

<= ![if !supportLists]>q   as with any operator, its argu= ments may be arbitrary expressions, as long as their values are of the right type=

<= ![if !supportLists]>q   the number of <value> expressions must equal the number of format specifiers in <format string>

<= ![if !supportLists]>q   the result is a string obtaine= d by replacing each format specifier in <format string> with the result of formatting the corresponding value in the way it specifies

<= ![if !supportLists]>n   Most progr= amming languages have a mechanism similar to this

 

Format specifiers &= nbsp;      

<= ![if !supportLists]>n     Syntax: %[<flag>][= <width>][.<precision>]<code>

<= ![if !supportLists]>q    here square brackets indicate optional syntactic elements

<= ![if !supportLists]>n     Four possibilities for <code= >

<= ![if !supportLists]>q    d for decimal (integer)

<= ![if !supportLists]>q    f for floating point (without a base-10 exponent)

<= ![if !supportLists]>q    g for floating point with exponent if needed

<= ![if !supportLists]>q    s for string

<= ![if !supportLists]>n     Three possibilities for <fla= g>

<= ![if !supportLists]>q    + to include numeric sign (+/-)=

<= ![if !supportLists]>q    - for left justification

<= ![if !supportLists]>q    0 for zero fill

<= ![if !supportLists]>n     <width> is the number of characters for the format

<= ![if !supportLists]>q    it will be longer if necessary<= o:p>

<= ![if !supportLists]>n     <precision> is the number= of digits after the decimal point of a floating-point number=

<= ![if !supportLists]>n&nb= sp;    %% inse= rts a single % in formatted text (“% escapes itself”)

<= ![if !supportLists]>n     There are more possibilities, b= ut these are the most useful

 

Handin

<= ![if !supportLists]>n   Crystal / Mud

<= ![if !supportLists]>q   list up to 3 things that are <= b>clear as crystal : it would be a waste of time for you if they were reviewed<= o:p>

<= ![if !supportLists]>q   list up to 3 things that are <= b>clear as mud: you’d like more class time on them

<= ![if !supportLists]>n   Don’t forget your signature and username, as in all handins

<= ![if !supportLists]>n   The follow= ing exercise

Exercise

<= ![if !supportLists]>n    Modify the growth.py application so it prints a nice table

Enter number of rows: 10=

 

 &nb= sp; n     n**2     &= nbsp; 2**n

 

 &nb= sp; 1        1        =   2

 &nb= sp; 2        4        =   4

 &nb= sp; 3        9        =   8

 &nb= sp; 4     &nbs= p; 16         16

 &nb= sp; 5     &nbs= p; 25         32

 &nb= sp; 6     &nbs= p; 36         64

 &nb= sp; 7     &nbs= p; 49        128

 &nb= sp; 8     &nbs= p; 64        256

 &nb= sp; 9     &nbs= p; 81        512

  10      100     &n= bsp; 1024

<= ![if !supportLists]>q   column widths are 4, 8, and 10<= o:p>

<= ![if !supportLists]>n    Answer: = growthTable.py

<= ![if !supportLists]>n    As always, if you’d like= me to check if your solution is correct, please show it to me after lecture<= /o:p>

 

growth.py

import math

def main():
    # not the best style, but showing that input is just a function
    for n in range(1, input('Enter number of rows: ') + 1):
        print n, n**2, 2**n

main()

Numeric literals

>>> -1234
-1234
>>> 1111111111111111111111111111111111111111111111111L
1111111111111111111111111111111111111111111111111L
>>> 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111L
111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111L
>>> 12.34
12.34
>>> 3e+100
2.9999999999999999e+100
>>> 1.0000000000000000000000000000000001
1.0
>>> 1+2e-3
1.00199999999999

Some built-in numeric functions

>>> type(1.)

>>> type(1)

>>> type(1L)

>>> int(5.6)
5
>>> float(5)
5.0
>>> long(5)
5L
>>> abs(-3.3)
3.2999999999999998
>>> abs(3.3)
3.2999999999999998
>>> max(3, 5.5)
5.5
>>> min(3, 5.5, 3.01)
3

Integer operators

>>> 3*3L
9L
>>> 1/2
0
>>> 25 % 12
1
>>> 18 % 12
6
>>> 79 / 25
3
>>> 79 % 25
4
>>> 2**8
256

Floating point operations

>>> 1./2
0.5
>>> int(5.6)
5
>>> round(5.6)
6.0
>>> from math import *
>>> sqrt(4)
2.0
>>> log(2**30, 2)
30.0
>>> log(e)
1.0
>>> sin(pi/2)
1.0

How big and small can Python numbers get?

>>> for n in range(32): print n, type(2**n)

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
>>> int(2**31)
2147483648L
>>> int(2**31-1)
2147483647
>>> _+1
2147483648L
>>> int(-2**31)
-2147483648
>>> int(_-1)
-2147483649L
>>> for n in range(1000000): x =3D 2.**n


Traceback (most recent call last):
  File "", line 1, in -toplevel-
    for n in range(1000000): x =3D 2.**n
OverflowError: (34, 'Result too large')
>>> x
8.9884656743115795e+307
>>> -x
-8.9884656743115795e+307
>>> for n in range(1000000): x =3D 2**n


Traceback (most recent call last):
  File "", line 1, in -toplevel-
    for n in range(1000000): x =3D 2**n
KeyboardInterrupt

>>> for n in range(1000000):
	m =3D n
	if 2. ** -n =3D=3D 0.0: break


>>> m
1075
>>> 2.**-1074
4.9406564584124654e-324

String literals

>>> "a string\
that's on a continued line"
"a stringthat's on a continued line"
>>> '''A multiline
string without
continued lines
'''
'A multiline\nstring without\ncontinued lines\n'
>>> print _
A multiline
string without
continued lines

>>> print '\ttab\ttab and \rreturn characters'
	tab	tab and 
return characters

Some built-in string functions

>>> ord('a')
97
>>> ord('b')
98
>>> ord('A')
65
>>> ord('0')
48
>>> ord('9') - ord('0')
9
>>> int('9')
9
>>> chr(48)
'0'
>>> chr(ord('x'))
'x'
>>> ord(chr(65))
65
>>> len('123')
3
>>> eval('2+2')
4
>>> eval('x =3D 3')

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    eval('x =3D 3')
  File "", line 1
    x =3D 3
      ^
SyntaxError: invalid syntax

String input

>>> username =3D input('Enter username: ')
Enter username: chaynes

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    username =3D input('Enter username: ')
  File "", line 0, in -toplevel-
NameError: name 'chaynes' is not defined
>>> username =3D raw_input('Enter username: ')
Enter username: chaynes
>>> username
'chaynes'

Sequence indexing

>>> s =3D 'a string'
>>> s[0]
'a'
>>> s[len(s)-1]
'g'
>>> s[len(s)]

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    s[len(s)]
IndexError: string index out of range
>>> s[0.3]

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    s[0.3]
TypeError: string indices must be integers
>>> s[2 : 4]
'st'
>>> s[2:]
'string'
>>> s[:-1]
'a strin'

Some functions in module string

>>> from string import *
>>> upper(s)
'A STRING'
>>> center('Title', 50)
'                      Title                       '
>>> rjust(33, 10)

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    rjust(33, 10)
  File "C:\Program Files\Python23\lib\string.py", line 259, in rjust
    return s.rjust(width)
AttributeError: 'int' object has no attribute 'rjust'
>>> rjust(str(33), 10)
'        33'
>>> strip(_)
'33'
>>> rstrip('  x  ')
'  x'
>>> replace('boo hoo', 'oo', 'aa')
'baa haa'

String formatting

>>> amount =3D 10.95
>>> print 'Tax', .05 * amount
Tax 0.54749999999999999
>>> print "Tax %.2f" % (.05 * amount)
Tax 0.55
>>> for n in range(21):
	print "%3d%8d" % (n, 2**n)


  0       1
  1       2
  2       4
  3       8
  4      16
  5      32
  6      64
  7     128
  8     256
  9     512
 10    1024
 11    2048
 12    4096
 13    8192
 14   16384
 15   32768
 16   65536
 17  131072
 18  262144
 19  524288
 20 1048576
>>> '.05%% of $%.2f is $d cents' % (amount, .05 * amount)

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    '.05%% of $%.2f is $d cents' % (amount, .05 * amount)
TypeError: not all arguments converted during string formatting
>>> '.05%% of $%.2f is %d cents' % (amount, .05 * amount * 100)
'.05% of $10.95 is 54 cents'
>>> 'Balance =3D %+.2f' % (amount)
'Balance =3D +10.95'
>>> 'Balance =3D %+.2f' % (-amount)
'Balance =3D -10.95'
>>> '%010d' % 8
'0000000008'
>>> '%010d' % 8 * 3
'000000000800000000080000000008'
>>> for n in range(10): print '%-8d|' % (2**n)

1       |
2       |
4       |
8       |
16      |
32      |
64      |
128     |
256     |
512     |
>>> s
'a string'
>>> print 'Character %d of "%s" is "%s"' % (3, s, s[3])
Character 3 of "a string" is "t"
>>>