• No results found

String Formats for Float Precision You generally do not want to display a floating point

In document Python 3 Hands-Oon.pdf (Page 46-53)

1.14. DECIMALS, FLOATS, AND FLOATING POINT ARITHMETIC

1.14.3. String Formats for Float Precision You generally do not want to display a floating point

result of a calculation in its raw form, often with an enormous number of digits after the decimal point, like 23.457413902458498. You are likely to prefer rounding it to something like 23.46. There are two approaches. First there is a format function (not method) with a second parameter allowed to specialize the formatting of objects as strings.. Read the following example interpreter sequence showing possibilites when a float is being formatted: >>> x = 23.457413902458498 >>> format(x, ’.5f’) >>> ’23.45741’ >>> format(x, ’.2f’) >>> ’23.46’

Note that the results are rounded not truncated: the result to two places is 23.46, not 23.45. The formatting string ’.5f’ means after the decimal point round to 5 places. Similarly ’.2f’ means round to two decimal places.

This rounding notation can also be placed after a colon inside the braces of format strings, for use with the string format method. Read the Shell session:

>>> x = 2.876543

>>> ’longer: {x:.5f}, shorter: {x:.3f}.’.format(**locals()) >>> ’longer: 2.87654, shorter: 2.877.’

The colon separates the symbol identifying what value to use for the substitution from the instructions for the specific formating method.

The colon and formatting instructions can also be used with the format versions depending on the order of the parameters. Continuing the earlier Shell example:

>>> ’No dictionary: {:.5f}.’.format(x) >>> ’No dictionary: 2.87654.’

There are many more fancy formatting options for the string format method that we will not discuss. Going to the opposite extreme, and using formatting with many digits, you can check that Python does not necessarily remember simple decimal numbers exactly:

>>> format(.1, ’.20f’) ’0.10000000000000000555’ >>> format(.2, ’.20f’) ’0.20000000000000001110’ >>> format(.1 + .2, ’.20f’) ’0.30000000000000004441’ >>> format(.3, ’.20f’) ’0.29999999999999998890’ >>>

Python stores the numbers correctly to about 16 or 17 digits. You may not care about such slight errors, but you will be able to check in Chapter 3 that if Python tests the expressions .1 + .2 and .3 for equality, it decides that they are not equal! In fact, as you can see above, the approximations that Python stores for the two expressions are not exactly equal. Do not depend on the exactness of floating point arithmetic, even for apparently simple expressions!

The floating point formatting code in this section is also in example program floatFormat.py.

Exercise 1.14.3.1. * Write a program, discount.py, that prompts the user for an original price and for a discount percentage and prints out the new price to the nearest cent. For example if the user enters 2.89 for the price and 20 for the discount percentage, the value would be (1- 20/100)*2.89, rounded to two decimal places, 2.31. For price .65 with a 25 percent discount, the value would be (1- 25/100)*.65, rounded to two decimal places, .49.10 Write the general calculation code following the pattern of the calculations illustrated in the two concrete examples.

1.15. Summary

Section numbers in square brackets indicate where an idea was first discussed.

Where Python syntax is illustrated, the typeface indicates the the category of each part:

Typeface Meaning

Typewriter font Text to be written verbatim

Emphasized A place where you can use an arbitrary identifier. The emphasized text attempts to be descriptive of the meaning of the identifier in the current context. Normal text A description of what goes in that position, without giving explicit syntax If there are several variations on a particular part of the syntax, alternatives will be show on successive lines.

To emphasize the successive parts of the syntax, space will generally be left around symbol and punctu- ation characters, but the space is not required in actual use.

(1) Python Shell

(a) A Shell window may be opened from the Idle menu: Run -> Python Shell [1.2.5] (b) Entering commands:

(i) Commands may be entered at the >>> prompt. [1.4.1]

(ii) If the Shell detects that a command is not finished at the end of the line, a continuation line is shown with no >>>. [1.4.2]

(iii) Statements with a heading ending in a colon followed by an indented block, must be terminated with an empty line. [1.13.4]

(iv) The Shell evaluates a completed command immediately, displaying any result other than None, starting on the next line. [1.4.1]

(v) The Shell remembers variable and function names. [1.6]

(c) An earlier Shell line may to copied and edited by clicking anywhere in the previously displayed line and then pressing Enter.

(2) Idle editing

(a) Start a new window from the File menu by selecting New, Open..., or Recent Files. [1.9.1] (b) Make your Python file names explicitly end with ’.py’ [1.6.1]

(3) To run a program from an Idle Editor Window:

(a) Select Run -> Run Module or press function key F5. The program runs in the Shell window, after resetting the shell so all old names are forgotten. [1.9.1]

(i) If the program is expecting keyboard input, the text cursor should appear at the end of the Shell history. If you somehow move the cursor elsewhere, you must explicitly move it back. [1.9]

10In Python 3.0+, the previous expressions make sense, but in earlier versions of Python and in other languages like C++

and Java, where there are not separate division operators // and /, these expressions would be wrong because of the multiple meanings of the operator / with different types. The expressions would work in these other languages if, for example, 100 were replaced by 100.0.

1.15. SUMMARY 48

(ii) BUG WORKAROUND: If you were running a program that was expecting keyboard input when you terminated it to start the latest run, you will need to start by pressing the Enter key once or maybe twice to clear the old pending wait for input. [1.9.2] (iii) Press Ctrl-C to stop a running program in a long or infinite loop.

(iv) After a program terminates, the Shell remembers function definitions and variable names define outside of any function. [1.11.2]

(4) Errors come in three categories:

(a) Syntax errors: text that the interpreter recognizes as illegal when first reading it. This prevents execution of your code. Python lets you know where it realized there was an error. Sometimes this is the exact location, but the actual error could be anywhere earlier, often on the previous line. [1.6]

(b) Execution errors: The first illegal action is detected while running your command or program. The source of the error could be in the line where execution fails, or it could be an earlier logical error that only later forces an execution error. [1.6]

(c) Logical errors: When Python detects nothing illegal, but you do not get the results you desire. These errors are the hardest to trace down. Playing computer and additional print functions help. [1.13.8]

(5) Type int, (short for integer):

(a) Literal integer values may not contain a decimal point. [1.14.1] (b) Integers may be arbitrarily large and are stored exactly. [1.14.1]

(c) Integers have normal operations, with usual precedence (highest listed first): (i) **: exponentiation (5**3 means 5*5*5) [1.14.2]

(ii) *, /,//, %: multiplication, division with float result, integer division (ignoring any re- mainder), just the remainder from division [1.4.3]

(iii) +, -: addition, subtraction [1.4.1]

(6) Type float, (short for floating point): approximations of real numbers

(a) Literal values must contain a decimal point to distinguish them from the int type [1.14.1] (b) Approximates a wide range of values [1.14.1]

(c) Does not dependably store numbers exactly – even numbers with simple decimal representation [1.14.1]

(d) Has the same operation symbols as for integers [1.14.1]

(e) A mixed binary operation with an integer and a float produces a float result. [1.14.1] (7) Type str, (short for string):

Literal values contain a sequence of characters enclosed in matching quotes. (a) Enclosed in ’or ": The string must be on one line. [1.5.1]

(b) Enclosed in ’’’or """: The string may include multiple lines in the source file. [1.8.1] (c) Escape codes inside literals include \’ for a single quote and \n for a newline. [1.8.2]

(d) Binary operations (operation symbols have the same precedence order as when the symbols are used in arithmetic)

(i) stringExpression1 + stringExpression2

concatenation (running together) of the two strings [1.5.2] (ii) stringExpression * integerExpression

integerExpression * stringExpression

Repeat the string the number of times given by the integer expression. [1.5.2] (e) string format method:

(i) stringFormatExpression.format(parameter0, parameter1, parameter2, ...) [1.10.4] where stringFormatExpression is any string with an arbitrary number of formatted sub- stitutions in it. Formatted substitutions are enclosed in braces. A digit inside the braces will indicate which parameter value is substituted, counting from 0. If digits are left out, the format paramters are substituted in order. The expression inside the braces can end with a colon (:) followed by a format specifying string such as:

.#f where # can be a non negative integer: substitute a numerical value rounded to the specified number of places beyond the decimal point. [1.14.1]

Example: ’A word: {}, a number: {}, a formatted number: {:.3f}.’.format(’Joe’, 23, 2.13579)

evaluates to: ’A word: Joe, a number: 23, a formatted number: 2.136.’ (ii) stringFormatExpression.format(**dictionary) The format expressions are the same

as above except that a key name from a dictionary appears inside the braces instead of a digit. The dictionary referenced appears int he parameter list preceded by **. The value to be substituted is then taken from the dictionary by accessing the key. Example: If defs is a dictionary with defs[’name’] equaling ’Joe’, defs[’num’] equaling 23, defs[’dec’] equaling 2.13579, then

’A word: {name}, a number: {num}, a formatted number: {dec:.3f}.’.format(**defs) evaluates to the same string as in the previous example. [1.12.2]

(f) Strings are a kind of sequence. (8) Type list

[ expression , expression , and so on ] [ expression ]

[]

(a) A literal list consists of a comma separated collection of values all enclosed in square brackets. There may be many, one, or no elements in the list. [1.13.2]

(b) A list is a kind of sequence, so it may be used as the sequence in a for-statement heading. [1.13.4]

(9) Type dict (short for dictionary) dict()

returns an empty dictionary

(a) A dictionary provides an association of each key to its value. The key can be any immutable type, with includes numbers and strings. [1.12.1]

(b) dictName [ keyExpression ] = valueExpression

associates in the dictionary dictName the key derived from evaluating keyExpression with the value derived from evaluating valueExpression. [1.12.1]

(c) Used in an expression, dictName [ keyExpression ] evaluates to the value in the dictionary dictName coming from the key obtained by evaluating keyExpression. [1.12.1]

(10) Type of None: This literal value has its own special type. None indicates the absence of a regular object.

(11) Identifiers

(a) Identifiers are names for Python objects [1.6.1]

(b) They may only contain letters, digits, and the underscore, and cannot start with a digit. They are case sensitive. [1.6.1]

(c) You cannot use a reserved word as an identifier, nor are you recommended to redefine an identifier predefined by Python. In the Idle editor you are safe if your identifier names remain colored black. [1.6.1]

(d) By convention, multi-word identifiers either [1.6.1]

(i) use underscores in place of blanks (since blanks are illegal is identifiers), as in initial_account_balance (ii) use camelcase: all lowercase except for the starting letter of the second and later words,

as in initialAccountBalance

(12) Variables are identifiers used to name Python data [1.6]

(a) When a variable is used in an expression, its latest value is substituted. [1.6] (13) Statements

(a) Assignment statement: [1.6] variable = expression

(i) The expression on the right is evaluated, using the latest values of all variables, and calculating all operations or functions specified.

(ii) The expression value is associated with the variable named on the left, removing any earlier association with the name.

(b) For-statement

1.15. SUMMARY 50

consistently indented statement block, which may use the variable item

For each element in the sequence, repeat the statement block substituting the next element in the sequence for the name variable name item. See Programming Patterns for patterns of use. [1.13.4]

(c) Return statement return expression

This is used only in a function definition, causing the function to immediately terminate and return the value of expression to the calling code, effectively acting as if the function call was replaced by this returned value. [1.11.6]

(14) Function calls

functionName ( expression, expression, and so on )

(a) The number of expressions must correspond to a number of parameters allowed by the func- tion’s definition. [1.11.4]

(b) Even if there are no parameters, the parentheses must be included to distinguish the name of the function from a request to call the function. [1.11.2]

(c) Each expression is evaluated and the values are passed to the code for the function, which executes its defined steps and may return a value. If the function call was a part of a larger expression, the returned value is used to evaluate the larger expression in the place where the function call was. [1.11.4]

(d) If nothing is returned explicitly, the function returns None.

(e) Function calls may also be used as statements, in which case any value that is returned is ignored (except if entered directly into the shell, which prints any returned value other than None).

(f) Keyword arguments are a special case. They have been used optionally at the end of the parameter list for print.

(15) Functions that are built-in (a) Print function: [1.7] [1.13.9]

print(expression)

print(expression, expression, expression)

print(expression, expression, expression, sep=stringVal, end=strVal) print()

(i) Print the value of each expression in the list to the standard place for output (usually the screen) separating each value by individual blanks unless the keyword argument sep is specified to change it. There can be any number of expressions (not just 1 or 3 as illustrated)

(ii) The string printed ends with a newline unless the keyword argument end is specified to change it.

(iii) With no expression, the statement only advances to a new line.

(b) Type names can be used as function to do obvious conversions to the type, as in int(’234’), float(123), str(123). [1.10.3]

(c) type(expression)

Return the type of the value of the expression. [1.5.1] (d) input(promptString)

Print the promptString to the screen; wait for the user to enter a line from the keyboard, ending with Enter. Return the character sequence as a string [1.10.1]

(e) len(sequence)

Return the number of elements in the sequence [1.3] (f) range(expression)

Require expression to have a non negative integer value, call it n. Generate a sequence with length n, consisting of the numbers 0 through n-1. For example range(4) generates the sequence 0, 1, 2, and 3 [1.13.3]

(g) max(expression1, expression2, and so on)

(h) format(expression, formatString) [1.14.1]

If expression is numeric, the format string can be in the form ’.#f’, where the # gets replaced by a nonnegative integer, and the result is a string with the value of the expression rounded to the specified number of digits beyond the decimal point.

(16) Functions defined by a user:

def functionName ( parameter1, parameter2, and so on) :

consistently indented statement block, which may include a return statement

(a) There may be any number of parameters. The parentheses must be included even if there are no parameters. [1.11.4]

(b) When a function is first defined, it is only remembered: its lines are not executed. [1.11.2] (c) When the function is later called in other code, the actual parameters in the function call are

used to initialize the local variables parameter1, parameter2, and so on in the same order as the actual parameters. [1.11.4]

(d) The local variables of a function are independent of the local names of any function defined outside of this function. The local variables must be initialized before use, and the names lose any association with their values when the function execution terminates. [1.11.8]

(e) If a return statement is reached, any further statements in the function are ignored. [1.11.6] (f) Functions should be used to :

(i) Emphasize that the code corresponds to one idea and give an easily recognizable name. [1.11.2]

(ii) Avoid repetition. If a basic idea is repeated with just the data changing, it will be easier to follow and use if it is coded once as a function with parameters, that gets called with the appropriate actual parameters when needed. [1.11.4]

(iii) It is good to separate the internal processing of data from the input and output of data. This typically means placing the processing of data and the return of the result in a function. [1.11.4]

(iv) Separate responsibilities: The consumer of a function only needs to know the name, parameter usage, and meaning of any returned value. Only the writer of a function needs to know the implementation of a function. [1.11.7]

(17) Modules (program files)

(a) A module may start with a documentation string. [1.9.4]

(b) Define your functions in your module. If the module is intended as a main program called only one way, a convention is make your execution just be calling a function called main. [1.11.3] (c) Avoid defining variable outside of your functions. Names for constant (unchanging) values are

a reasonable exception. [1.11.9]

(18) Documentation String: A string, often a multi-line (triple quoted) string that may appear in two places:

(a) At the very beginning of a file: This should give overall introductory information about the file [1.9.4]

(b) As the very first entry in the body of a function: This should describe: [1.12.1] (i) The return value of the function (if there is one)

(ii) Anything about the parameters that is not totally obvious from the names (iii) Anything about the results from the function that is not obvious from the name (19) Programming Patterns

(a) Input-calculate-Output: This is the simplest overall program model. First obtain all the data you need (for instance by prompting the user for keyboard input). Calculate what you need from this data. Output the data (for instance to the screen with print functions). [??] (b) Repetitive patterns: These patterns are all associated with loops. Loops are essential if the

number of repetitions depends on dynamic data in the program. Even if you could avoid a loop by repeating code, a loop is usually a better choice to make the repetitive logic of your program clear to all.

(i) Exact repetition some number of times: If the number of time to repeat is n: for i in range(n):

1.15. SUMMARY 52

Here the variable i is included only because there must be a variable name in a for-loop. [1.13.5]

(ii) For-each loop: Do the same sort of thing for each item in a specified sequence. [1.13.4] for item in sequence :

actions to be done with each item

(iii) Successive modification loop: Repeat a basic idea, but where the data involved each time changes via a pattern that is coded in the loop to convert the previous data into the data needed the next time through the loop [1.13.6]:

initialize all variables that will be successively modified in the loop loop heading for the repetition :

actions to be in each loop with the current variable values

modify the variable values to prepare for the next time through the loop (iv) Accumulation loop: A sequence of items need to be combined. This works where the

accumulation of all the items can be approached incrementally, combining one after another with the accumulation so far [1.13.7]:

initialize the accumulation to include none of the sequence for item in sequence :

new value of accumulation =

result of combining item with last value of accumulation

(20) Playing computer: testing that you understand your code (and it works right or helping you find where it goes wrong) [1.13.1,1.13.6, 1.13.8]

(a) Make sure line numbers are labeled

(b) Make a table with heading for line numbers, all variables that will be changing, and comments (c) Follow the order of execution, one statement at a time, being careful to update variable values and only use the latest variable values, and carefully following the flow of control through loops and into and out of function calls.

In document Python 3 Hands-Oon.pdf (Page 46-53)