CS 1110 - Introduction to Programming

Starting Out with Python
Chapter 2, Input, Processing, and Output

Objectives:

This lesson covers a lot of material. It introduces several concepts that relate to all programming languages, showing you how such things work in Python. Objectives important to this lesson:

  1. Designing a program
  2. Input, processing, and output
  3. Displaying output
  4. Comments (remarks)
  5. Variables
  6. Keyboard input
  7. Calculations
  8. Data output
  9. Constants
Concepts:
Chapter 2

A program that doesn't do much can be written without much planning. A program that will do a lot of important things had better be planned out before you start writing lines of code, or you run the risk of getting lost, leaving out important features, or just writing a program that does not work. We avoid those problems by creating a design, a plan for the program, before we write the actual code.

A diagram on page 31 shows us a series of five steps that can lead to a better program.

  1. Design - What must the program do? Where will it get its data? Will it interact with the user? How will it process the data? Where will it send its output? Typically, you answer these questions and several others before you draw a diagram of how the program should work.
  2. Code - Write the first version of the program, following the plan you just made.
  3. Look for and correct syntax errors - Syntax errors are errors in spacing, punctuation, spelling of reserved (key) words and commands, or any other error that violates the rules of the language itself. Where is there an error? Sometimes you can't know until you try to run the program, so feel free to swap steps 3 and 4.
  4. Test the program - Run the program against data whose result can be predicted. Does it work?
  5. Look for and correct logic errors - Logic errors are what happen when you tell the program to do the wrong thing, or do not tell it to do the right thing. If the program does not work properly, what went wrong? Is the design wrong? Is the code wrong? What did you tell it to do that should have been something else? What was left out that should have been done?

In each of the steps above, it is important to know what the program should do. In the beginning, you ask a lot of questions to your customer. In the discussion on page 33, the text give us two examples of writing out the steps without actually writing lines of code. This is what we do when we use pseudocode. We write descriptions of what happens in each step of a process, meaning to translate those descriptions into a programming language once we are sure about the accuracy of our pseudocode.

Pseudocode is easier to do than flowcharting. When we make a flow chart, we have to use specific symbols that stand for particular kinds of steps. In the example on page 35, the book shows us a flow chart with three kinds of symbols: ovals for start and end point of the flow, parallelograms for input and output, and a rectangle for processing. There are rules about flowcharting that get a lot more complicated, but this method is a good start. Flowcharting is more useful when your programs are more complicated and you understand more symbols.

The bottom of page 35 shows us three rules that define three ideas:

  • Input is something the program receives, usually from the user or from a file.
  • Processing is what happens when the program does something with the input.
  • Output is something the program produces, usually to a screen, to a file, or to both.

The text shows this information as a numbered list, which is also correct. The steps are usually performed in that order, so numbering the bullets above as 1, 2, and 3 would also be right.

In chapter 1, we saw that we can send output to the screen with one of python's built-in functions, the print function. What is a built-in function? It is a short program that the language already knows how to run. We call a function, that is, we tell it to run, either on a command line or as a command inside one of our own programs. Let's go back to discussing the print function.

  • print is the name of the function.
  • The name is followed by a set of parentheses.
  • Inside this set of parentheses is a series of characters (usually called a string, a literal, or a string literal), and the string is enclosed by single quotes in the example on page 36.
  • What we place inside the parentheses of a called function is called the argument, the data that the function needs to do something for us.
  • As the text explains, the single quote characters are just markers for the beginning and the end of the string.
  • As the next page shows, we could have used double quotes (also just called quotation marks) instead of single quotes, but we must use the same kind of quote character at each end of the string.

The text explains that the instructions above are modified slightly when the string you want to print includes apostrophes, single quotes, and or double quotes in any combination.

  • If your string only includes single quotes (apostrophes), mark the start and end of the string with double quotes. ("this example is John's")
  • If your string only includes double quotes (quotation marks), mark the start and end of the string with single quotes. (This string is about "Game of Thrones" and other shows')
  • If your string includes both kinds of quotes, or even if it doesn't have any, you can use three quotation marks or three apostrophes as your beginning and end markers. Whichever you choose, use the same kind at each end. This notation can also be used when your string includes line returns. The line returns are preserved in this notation, but they are not in the other two notations.

Programs are easier to change, to debug, and to use when we know what they are supposed to be doing. This is why someone invented the idea of internal documentation, also called comments or remarks. Your text calls them comments. They are notes that the programmer puts inside the program as a reminder to him/herself about what a section of code does, about a revision, or about anything that needs to be understood at that part of a program. Comments are not recognized as commands, so the interpreter just ignores them.

Python uses the # character as a comment marker. By the way, that character has several names, which the text avoided mentioning. It is a pound sign, a number sign, a crosshatch, a hash mark, and an octothorp. In Python, everything that appears after this character on a single line is a comment.

This takes us to the land of math. Breathe deeply, it will all be fine. The first concept is about variables.

A variable is a named space in memory where something can be stored, read, changed, or erased. You can create a variable and initialize it at the same time. To initialize it is to store something in it for the first time. On page 40, we are given an example:

age = 25

Entering this statement as a line in a program creates a variable in memory called age, and then stores the value 25 in it. The equal sign is called an assignment operator because it assigns the value on its right to the variable on its left. You can't enter a command like 25 = age, because the equal sign works from right to left, and even if age held a value at this moment, the equal sign could not assign a value to an actual number. Who would want to redefine what 25 means? The text says you can't assign a value to a literal, which is also true, but I think this makes the point better.

If we want to display the value stored in the variable called age, we can use the print function to do that. Print(age) would put the value stored in the age variable on the screen. If we wanted to display the word age, we would use a command like print('age'), which would print the characters inside the single quotes. There are several ways to print literals and values on the same line. One is shown on page 45.

age = 25
print('The value of the variable age is', age)


This prints the literal string, inserts a space because of the comma, then prints the value of the variable.

Rules about Python variable names:

  • variable names are spelling and case sensitive, so always spell them the same way and use the same capitalization, unless you mean a new spelling/capitalization to be a different variable
  • you can't use key words as variable names
  • you can't use spaces in variable names
  • you can use letters, digits, and underscores in variable names, but they cannot begin with digits

There is no rule that says your variable names have to make sense, but it is silly not to choose names that make sense.

Sometimes, you will want to use more than one word in a variable name. The text recommends that we use names like smart_name instead of names like smartname, because they are easier to read. The text also mentions a different naming convention that it does not recommend called camelCase. It is known by other names, and it not universally agreed upon that the first letter must be in lower case, so that makes it harder to follow that style and please everyone.

As noted above, the values stored in variables can be changed with a new assignment statement. This is illustrated on pages 45 and 46. The text refers to this as performing a reassignment.

So far, we have not considered what kind of value will be stored in a variable. It does not have to be a number. Even if we only consider numbers, there are different kinds. Two types are mentioned on pages 46 and 47. A number with no decimal point is stored in a type of variable called an int, which is an abbreviation of the work integer. A number that has a decimal point is stored in a variable type called a float, which means that the decimal point can float back and forth in the series of digits, depending on what we do to that value. Doing a math operation (such a division) with integers may not result in the same answer as doing the same operation with floats, because integer math tends to round off the answers. Note the example on page 47 showing the use of the type function, which can tell us whether a number would be treated as an int or as a float.

Values that are not numeric are often treated as strings. A string is a sequence of characters that may be of almost any length. On page 48, the text shows us that we can assign a word or a sentence to a variable. It also show us that we can initialize a variable with an integer
x = 99
which would make the variable x of type int. However, if we reassign a string to the variable
x = "This is a string."
that would make the variable called x into a variable of type str. Other languages are not this flexible, but Python does not complain about such things.

It is often necessary for a program to ask a user for input. Python has an input function that allows us to ask for a single input that will be assigned to a variable as a string. Example:
variable_goes_here = input('Ask your user a question here")
In this case, the program would put the string inside the single quotes on the screen, and wait for the user to type something, ending with the enter key. The string the user typed would be stored in the named variable on the left of the equal sign. Again, the input from the user ends with the first press of the enter key.

Since the input function stores what it captures as a string, we cannot do math with what is stored in its variable. When we need to do math with what was captured, we can use the int() function to save the input in an int variable, or the float() function to store the input in a float variable. These actions assume that what you are capturing is supposed to be numeric data. The bottom of page 51 shows how to nest the input() function inside the int function, resulting in only needing one variable to do the job:
hours = int(input('How many hours did you work? '))
Again, this would only work if the users play by the rules and enter numbers when we expect them to do so. You will learn about error trapping programs later. For now, remember that the int() function will truncate a float if that is what it is given.

This takes us to the program example on page 52. The functions discussed so far are illustrated. On the next page we see an example of the program running without user cooperation. I ran the program, entered my last name for the age response, and it failed as expected:

So, with these basic instructions understood, the text takes us into doing some math. Page 54 shows us a table of some of the math operators you can use in Python. A couple of the may look unfamiliar.

Symbol Operation it performs Say what?
+ addition  
- subtraction  
* multiplication  
/ division  
// integer division 5 // 2 would be 2 because only the integer portion of the answer is produced
% remainder, also called modulus 5 % 2 would be 1. The operator puts the number on the right into the number on the left as many times as possible, then reports the remainder. This is useful in programs that calculate how many of each type of coin to give in change.
** exponent 5 ** 2 would be 25. It means 5 raised to the 2nd power (5 * 5).

 

An example of integer division is shown on page 56. 5 / 2 is shown to produce 2.5, which is correct. As noted in the table above, 5 // 2 produces 2, because when the answer is positive, the answer is truncated. This means the decimal portion of the answer is discarded. If the problem had produced a negative answer, as we get from -5 // 2, the answer is rounded down to the next integer. In both cases, we could say that the answer was rounded down to the next lower integer.

The next section of the chapter is background information that will help you with most computer math. Computers typically follow an order of operations that follows the mnemonic phrase "Please excuse my dear Aunt Sally".

Please
Evaluate items in parentheses first.
excuse
Evaluate any exponents next.
my
Do any multiplication as the third step.
dear
Do any division as the fourth step.
Aunt
Do any addition as the fifth step.
Sally
Finally, do any subtraction.

Multiplication and division are actually at the same level of precedence, and addition and subtraction are at the next level down. When you only have on level of precedence, then you go left to right. Following Aunt Sally's order of operations, the computer would examine the problem shown on the bottom of page 57 like this:

outcome = 12.0 + 6.0 / 3.0

Divide 6.0 by 3.0, producing 2.0. Add 12.0 and 2.0, producing 14.0 The result is then assigned to the variable.

So, when you want something done in a particular order, don't assume you know how the computer will do it or that the next programmer who troubleshoots your code will understand. Use parentheses, which are at the highest level of precedence, to group the actions you want a calculation to take, in the order you need them taken. The examples on pages 58 and 59 show proper use of parentheses to control order of operation in an equation.

On page 63, the text explains something you may have noticed about equations that contain more than one type of operand. Typically, the result of such an operation is to take on the type of the more complex operand. Operations that control the type of their result are exceptions. The rules on page 63 explain this:

  • When an operation is performed on two int values, the result wll be of type int.
  • When an operation is performed on two float values, the result will be of type float.
  • When an operation is performed on operands that are type int and type float, the operand that is type int is promoted (only during the operation) to type float, resulting in an answer that is type float.

Let's move ahead to page 65, where the text discusses something else you may have noticed. When you use the print() function, it automatically provides a line return after printing the material in its parentheses. This is a default that is usually fine, but sometimes you don't want that to happen. The text shows us two ways to suppress the newline feature by replacing it with something else for a particular print().

  • print("This puts a space at the end", end=' ')
    This would print out the string that you see, the end the line with a space, which is the character enclosed by the two single quotes.

  • Print("This keeps the cursor at the end of the text", end='')
    This one is hard to see on a web page. The print() function would print out the given string, then the end= option would put nothing after the last character. In this case the end= option was given two single quotes with nothing between them.

The print() function has another useful option. The default behavior when printing multiple arguments with one command is to separate them with spaces. Again, this is fine when that's what you want. When you want the command to use something other than a space as a separator, use the sep= option to specify a character
print("string", "string", "string", sep=",")

or to specify no character
print("string", "string", "string", sep='').

Page 67 shows us a list of five special characters that modify the next thing the print() function does. They control output or print otherwise hard-to-print characters where they appear in print strings. These are known as escape characters, perhaps because they escape the normal behavior of the print() function.

\n
Print the newline character.
\t
Prints a tab character.
\'
Prints an apostrophe.
\"
Prints a quotation mark.
\\
Prints a backslash.

 

On the bottom of page 68, the text begins a section about formatting numbers. For instance, you may want to control how many digits of a floating point number are printed. This is particularly true when you print numbers that are associated with payments, like the example on page 68. The payment printed by that example would not be acceptable. The format() function is discussed on the next page. We can hand it two arguments: a number (or a variable that holds a number) and a control string that tells format how to handle the number. For example: print(format(5000.0 / 12, '.2f'))

In the image above, I issued the command in the IDLE window. Note that the key words are purple, the math phrase is black, and the format string is light green. This makes it easier to see that each part is doing something different for us. In this case, the output of the print() function, is blue. The .2 in the control string formated it to two decimal places, and the f told the format() function that it was dealing with a float. Since it was a float, rounding took place, not truncating, which would have happened with a string. More formatting information is presented through page 73,

At the bottom of page 73, we begin a section about constants. It begins by introducing us to another internal documentation concept. You already know that variables can be given meaningful names. So can constants, named memory locations that hold values that, unlike variables, are not meant to change. Well, if it is a constant, why not just use the number it stands for? In the example in the text, we see a number that may stand for an interest rate, a fee basis, or anything else that might make sense. The text refers to this as a magic number, because it is doing something but we can't point to a comment or a label that tells us its purpose. The text recommends that we use named constants for such purposes. This makes it easier to make global replacements if they are used numerous times in a program, as well as reducing the chance of typing an actual number incorrectly one or more times in that numerous herd of numbers. It is a common convention in several languages to name such a constant with a name whose letters are all capitals. This makes it easier to find usages of such constants, since they stand out in lines of code that are mostly lower case.

Assignments

Assignments for these chapters will be found in Blackboard. We will explore that in class.