Spring 2012 CSCI 220 Week 2 TBP

Software Development

 * Writing large programs can be a daunting challenge
 * Need a systematic approach
 * Programming Process is often broken down into stages:
 * 1) Analyze the problem
 * 2) Determine Specifications
 * 3) Create a design
 * 4) Implement a design
 * 5) Test/Debug
 * 6) Maintain the program

Problem
Develop a program that will translate Celsius into Fahrenheit using the temperature announced on the radio so that an appropriate outfit can be selected based on the weather conditions.

Specifications
What are we trying to accomplish?

Do we need speech recognition?

How about a robot to get the close out of the closet?

Design
Write our first pseudocode, which is precise English that describes what a program does. It is meant to communicate the algorithm without implementation details. Input the temperature in degrees Celsius (call it celsius) Calculate fahrenheit as (9/5)celcius + 32 Output fahrenheit

Implement the design (in class exercise)

 * 1) convert.py
 * 2) A program to convert Celsius temps to Fahrenheit

def main: celsius = eval(input("What is the Celsius temperature? ")) fahrenheit = 9/5 * celsius + 32 print("The temperature is", fahrenheit, "degrees Fahrenheit")

main

After completing the program we test our implementation
Try 0 degrees Celsius, which is 32 degrees Fahrenheit. Also, try 100 degrees Celsius, which is 212 degrees Fahrenheit.

Names

 * We give names to modules (e.g., chaos.py)
 * We give names to functions within modules (e.g., main)
 * We give names to variables (e.g., celcius)

Technically, these names are know as identifiers

Python like other languages have rules for their construction:
 * Must begin with a letter or underscore
 * That may be followed by any sequence of letters, digits, or underscores
 * Cannot contain spaces
 * Case sensitive

Some legal names:
 * x
 * celcius
 * SpamAndEggs
 * _celcius
 * Spam_And_Eggs

Good programmers always try to choose descriptive names

NOTE: Some identifiers are part of Python itself. These names are reserved words or keywords and cannot be used as ordinary identifiers. The complete list of Python keywords is Table 2.1.

Expressions
An expression is a fragment of program code that produces or calculates new data values.

Simplest kind of expression is a literal, which is used to indicate a specific values. Our convert program contains 9, 5, and 32. All of them are numeric literals. There are also string literals in our convert.py program. Note that the quotes are not part of the string. They just tell python to create the string.

Process of turning expression into underlying data type is called evaluation.

Some simple expressions: >>> 32 32 >>> "Hello" 'Hello' >>> "32" '32'

Simple identifiers as expressions: >>> x = 5 >>> x 5 >>> print(x) 5 >>> print(spam) Traceback (most recent call last): File "", line 1, in    print(spam) NameError: name 'spam' is not defined

More complex expressions using operators (spaces do not matter): >>> 3.9 * x * (1 - x) >>> 9/5 * celcius + 32

Python provides the normal set of operators:
 * addition is +
 * subtraction is -
 * multiplication is *
 * division is /
 * exponentiation is **

Python's operators obey the same rules of precedence that you learned in math class. You can modify the order of evaluation with parentheses, but only round parentheses.

Python can also operate on strings (i.e., concatenation) >>> "Dr. " "Paul " + "Anderson" 'Dr. Paul Anderson'

A closer look at print
Two forms of print print(, , ..., ) print

The bracket notation (<>) indicates slots that are filled in by other fragments of Python code. The name inside the brackets explains what is missing; expr stands for an expression. The ellipses indicates an indefinite series. You do NOT type the dots.

That was a description of its syntax. The semantics are that a print statement displays information in textual form. By default a single blank space is placed between the displayed values. >>> print(3+4) 7 >>> print(3, 4, 3 + 4) 3 4 7 >>> print

>>> print("The answer is", 3 + 4) The answer is 7

Print automatically adds a special marker character (denoted as "\n") that signals the end of the line. We can modify this by adding an additional parameter. This is done with special keyword parameters. Here is a template: print(, , ..., , end = "\n")

Here is an example of adding a semicolon at the end of the line >>> print("The answer is", 3 + 4) The answer is 7 >>> print("The answer is", 3 + 4, end = ";") The answer is 7;

Simple Assignment
Basic assignment statement has the form: = where variable is an identifier and expr is an expression. The right side is evaluated and then the result is associated with the left side of the equal sign.

A variable can be assigned many times, but it only retains the value of its most recent assignment. >>> myVar = 0 >>> myVar 0 >>> myVar = 7 >>> myVar 7 >>> myVar = myVar + 1 >>> myVar 8 The last assignment shows that you can use the current value of a variable to update its value. This was done in the chaos.py program from last week.

It is useful to think of storage location in memory as a box we can put a value in. Assigning a variable is like putting those yellow sticky notes on the value and saying, "this is x." When you assign a new value to x, the sticky note is moved, but the previous value is still in memory (until garbage collection). See Figure 2.2.

Assigning Input
Purpose of input is to get information from the user and store it into a variable.

For textual input: = input When Python encounters an input statement, it prints the prompt on the screen and pauses until some text is entered and the user presses the  key.

Example: >>> name = input("Enter your name: ") Enter your name: Paul >>> name 'Paul'

When asking the user to input a number, we need a slightly more complicated form of the input statement: = eval(input) where eval is short for evaluate, which tells Python to evaluate the expression that was entered.

Example: >>> x = eval(input("Enter a number between 0 and 1: ")) Enter a number between 0 and 1: 0.5 >>> x 0.5

This is allowed between we have an interpreted language, so we can get creative: >>> ans = eval(input("Enter an expression: ")) Enter an expression: 3 + 4 * 5 >>> ans 23 >>> ans = eval(input("Enter an expression: ")) Enter an expression: "Paul" >>> ans 'Paul'

Simultaneous Assignment
,, ..., = , , ...,

Example: >>> sum, diff = 1+2, 1-2 >>> sum 3 >>> diff -1

What might seem strange at first is very useful. Say you have two variables (x and y), and you want to swap the values of them. You might try: >>> x = 1 >>> y = 2 >>> x = y >>> y = x >>> x 2 >>> y 2 But that doesn't work.

This is a common task in programming, and without simultaneous assignment, we need a temporary variable: >>> x = 1 >>> y = 2 >>> temp = x >>> x = y >>> y = temp >>> x 2 >>> y 1

With simultaneous assignment, we only need one statement: >>> x = 1 >>> y = 2 >>> x, y = y, x >>> x 2 >>> y 1

Simultaneous assignment can also be used to get multiple values from a user using one input statement:


 * 1) avg2.py
 * 2) A simple program to average two scores

def main: print("This program computes the average of two scores.")

score1, score2 = eval(input("Enter two scores separated by a comma: ")) average = (score1 + score2)/2

print("The average of the score is:", average)

main

Output: This program computes the average of two scores. Enter two scores separated by a comma: 2, 4 The average of the score is: 3.0

Definite Loops
Programmers use loops to execute a sequence of statements multiple times in succession. The simplest loop is one that executes a definite number of times. Example: x = 0.25 for i in range(10): x = 3.9 * x * (1 - x)   print(x)

A Python for loop has the general form: for in :

The body can be any sequence of Python statements. The part of the code in the body is defined by the indentation. The variable after the keyword for is the loop index. It takes on each successive value in the sequence, and the statements in the body are executed once for each value. Often the sequence is a simple list of values: >>> for i in [0,1,2,3]: print(i)

0 1 2 3

Now we know that range(10) must be some kind of sequence. We can examine this sequence by typing: >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Note that range starts at 0 by default and does not go all the way up to 10. If you wanted this behavior, you can modify the statement as such: >>> list(range(1,11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The interesting and useful thing about loops is that they alter the flow of the program. Introducing a loop causes Python to go back and do some repeat some statements over and over again. See Figure 2.3 for a flowchart diagram of this process.

Extra in class assignment

 * 1) Write a program that converts distances measured in kilometers to miles. One kilometer is approximately 0.62 miles.


 * 1) Write an interactive Python calculator program.