CS 110X Jan 21 2014
Expected reading: pages 27-39.
Expected interaction:
String types
Clicker: Assessment
We are what we repeatedly do. Excellence, then, is not an act, but a habit. Aristotle
1 Well Begun Is Half Done
In this lecture I will set out the basic structure of every program that you are going to write for this course. In doing so, I want to get you into a specific habit, which will help you when it comes time to complete the class assignments and future programming efforts.
The Voyager computation from last week was such a
success! Your NASA manager now wants you to write a program that computes
the current distance of any space probe with just the following pieces of
information:
1. Last recorded distance of probe
2. Last known probe velocity (in mph)
3. Number of days since last probe reading
1.1 Programming
You have already done this computation manually (see Jan 17 2014 lecture); the trick, now, is to avoid having to write a new program for each space probe being tracked by NASA.
What you need is a way for the user to input from the keyboard the required pieces of information. With this information, your program must process the data using appropriate computations. Then it must output the proper answer in a format expected by the user.
In programming, this is known as the input - process - output structure.
Input – Information is provided to the program, either as keyboard input or loaded from a file on disk
Processing – The program performs the calculations as demanded by the requirements
Output – Information is output to be either viewed by the user on the console output window or saved to a file on disk
In this lecture, I will show you how to answer the Voyager problem, and in doing so, present a template that you will use for the rest of this class when you write Python programs.
Throughout the book, the author uses eval(input("some prompt")) to read information from the user. UNFORTUNATELY, this capability was only added to Python v3.0 and we are using v2.7.3. Simply omit the eval(...) and use just input(...)". For more, see Differences between 2.7 and 3.0
But first, let’s figure out how to get input from the user. In an IDLE shell window, type the following:
x = input()
Your shell window should pause (with a blinking cursor) waiting for you to enter in some text. Be nice and type a number, such as 137.23, and press return. The >>> prompt reappears. Now type print(x) in the window and you should see the value 137.23 returned to you.
What you have done is request the user to enter in some information, and the value typed by that user is converted into a proper Python value, which is stored in variable x. Of course, the user will have no idea of what to do with a blinking cursor, so you need to prompt the user with some text. The following addition will do the trick.
x = input("Enter a Number ")
When you type the above code (note the extra " " SPACE after Number) you will see the prompt string appear before the blinking cursor (and the extra space helps separate the prompt from the user input). At least now a user has an idea of what is expected.
As you might recall from last lecture, the string "Enter a Number " in quotes is a string literal. Like most programming languages, Python lets you create string literals that represent ordinary text that is not interpreted by Python in any way. Usually these strings are meant for humans to more easily understand what a program is trying to do.
1.2 Explanation
We are now ready to put everything together into one program. I’ll show it to you first:
I am no longer going to include ⇒ annotations in the code sample to show indentation.
With the judicious use of comments, you can see that the main method now has three distinct phases. In the input phase, the user is prompted for three pieces of information, which are immediately stored in three variables, distance, speed, and days.
Be sure to pay close attention to units associated with values! NASA lost a 125 million dollar Mars Climate Orbiter because two international teams shared data using different measurement systems
The output phase also is restricted to a single line.
As constituted, this program properly computes the desired result, but the output needs better formatting (much like we did for the input). To explain how to do this, we need to introduce a new concept.
1.3 String Concatenation
In the same way that you have learned to perform computations over numbers (both integers and floats) you can also perform some simple computations using strings.
The most popular operation is concatenation which allows you to combine two or more strings together using the + operator to form a new string. Type the following in a Python shell window to see how this works.
"CS" + ’110X’
Python should reply with the string literal ’CS110X’. In Python, you can use either single quotes (’) or double quotes (") to delimit string literals – just make sure you open and close with the same type.
To be precise, the + operator above takes two str values (’CS’ and ’110X’) and produces a new str value (’CS110X’).
So it looks like the output should be formatted something like 11434150789 miles. Try the following.
print (location + " miles")
If you do this and run the program, you will notice an error reported by the Python interpreter:
Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> main() File "C:\Users\Laptop\Dropbox\cs110x\days\day03\voyager_now.py", line 14, in main print (location + " miles") TypeError: unsupported operand type(s) for +: ’int’ and ’str’
So in Python you can use the + operator to add together two numbers (floating points values or int values). You can also use + to concatenate two string values. However, you can’t perform "mixed-mode" concatenation. Fortunately, there is an easy way out, as we will see next.
1.4 Converting Values Into Strings
Given any Python value, you can immediately convert it into a string value using the str(...) function. For example.
>>> x = 3.54 >>> print (x) 3.54 >>> s = str(x) >>> print (s) ’3.54’
See how these are different? The first value output is the floating point value 3.54 whereas the second value output is a string of four characters, which humans can interpret to be a floating point value.
In fact, you could combine the above to be more concise:
>>> x = 3.54 >>> print (str(x)) ’3.54’
The python statement print (str (x)) reads in English as follows: "Print the result of calling the str() function with x as an argument". Python interprets this statement by first evaluating x, which is the value 3.54, and then calling str(3.54) to produce the value ’3.54’, which is then printed to the console window by the print function.
Once you see how to convert Python values into strings, then you can immediately use the string concatenate + operation to combine multiple string fragments together into a single string.
Now change the program to read as follows:
# Assignment: Lecture Example # Author: George Heineman def main(): # input distance = input("Last recorded distance of probe ") speed = input("Last known probe velocity ") days = input("How many days since last reading ") # processing location = distance + speed * days * 24 # output print ("The probe is now at a distance of " + str(location))
When you run this program, the output is formatted as we would like.
Be careful to include the extra "space" within the string literal to avoid having the location run up against the string.
You can use concatenation multiple times, such as:
print ("The probe is now " + str(location) + " miles away, moving at " + str(speed) + " mph")
As you can see, this approach leads to long Python statements. I recommend that you break these long statements up into smaller ones. One approach is to incrementally concatenate values into a specific variable, which is then printed. For example, the above could "grow" a string as follows:
s = "The probe is now " + str(location) s = s + " miles away, moving at " s = s + str(speed) s = s + " mph" print (s)
The above might look odd at first, but reflect on the nature of the = assignment operator. When you see the statement x = 5, you should think "x gets the value of 5". The left-hand side of the statement (the variable x) will now have the value computed by the right-hand side of the statement (the int value 5).
Now when you see the statement x = y + 5 you should think "x gets the value of y plus 5".
So when you see the statement x = x + 5 you can think "x gets the value of x plus 5" and there is no confusion or paradox. To use precise terms, the = operator does not behave like the "equal" operator in mathematics where it would be a contradiction to say "x is equal to x + 5".
1.5 Main function
In earlier Python modules that we wrote, I felt free to name the variables and functions however I chose. However, there is a universal standard that you will use for many of the program assignments you complete in this course.
When you create a module with a function called main, it is understood that this function is the one that you want to execute.
On page 13 of the textbook, the Python module chaos.py contains a main method. It goes one step further in that when you import or execute this module, the main method will automatically execute because the last line of the chaos.py module contains the Python statement main() which invokes the main method immediately.
Below is the modified Python 2.7.3 version of the chaos.py module found in the book.
# File: chaos.py # Author: John Zelle # A simple program illustrating chaotic behavior. def main(): print ("This program illustrates a chaotic function") x = input("Enter a number between 0 and 1: ") for i in range(10): x = 3.9* x * (1 - x) print (x) # this executes the function just defined main()
Enter this into a new window in IDLE and save it to disk as chaos.py. Now when you select Run -> Run Module the program immediately executes because the final line in the module invokes main().
After the first exam, you will begin to define Python modules that auto-execute once run.
1.6 Definite for Loop
In the chaos.py module, you can see a new Python statement known as the definite for loop. This will be covered in lecture on Jan 23 2014.
1.7 Debugging Challenge
Our programs are becoming more complicated, but they will all follow the input - process - output process.
The following Python function tries to prompt the user to enter in an (x,y) Cartesian coordinate. The program computes the distance from this point to the origin (0,0).
Press To Reveal
Defects
1.8 Skills
In this lecture you learned about string literals and the use of input/output in the IDLE Shell window. You saw how to write a program with a standard main() method. You learned how to invoke print with multiple arguments.
IO-1: Know how to print information to the console window
SM-2: Know how to convert floats and integers into string
SM-3: Know how to concatenate string literals
PF-1: Know how to define a function
PM-1: Understand how to define a function within a module
Be sure you understand how the following assignment operation works.
x = x + 5
If you try to read this "Mathematically" you will be confused, because there is no number x which is equal to itself plus 5.
Rather you must read this "Computationally" in which case you would translate it as "Set the new value of x to be its current value plus 5". Thus when you see the "=" operator you should think "Assignment". More specifically, the variable identified on the left hand side of the "=" has its value changed to the value of the expression on the right hand side.
1.9 Self Assessment
Recall the Self Assessment question from the Jan 17 2014 lecture? Take that program and have the user enter in the fixed constants for P, V and T so you can compute n. Note that you can assume the user types in the values using the proper units. Be sure to prompt for each value using the appropriate prompt string, and include the necessary comments.
When completing this self assessment, be sure to add proper comments, both at the start of the Python module, as well as within the function.
1.10 Version : 2014/01/22
(c) 2014, George Heineman