Chapter 3

NUMERIC DATA


Topics Covered:

  • Data types
  • Numeric operators
  • Precedence rules
  • Assignment
  • Error types

“I think that great programming is not all that dissimilar to great art. Once you start thinking in concepts of programming it makes you a better person…as does learning a foreign language, as does learning math, as does learning how to read.”

– Jack Dorsey, Twitter creator and founder and Square CEO

Data Types

Ultimately, everything that is stored within a computer’s memory is a number. The computer’s processing unit has to decide, based on context, what the numbers in the memory represent. If the CPU is asked to execute the instruction at memory location 385, the CPU assumes that the number stored in that memory location should be treated as a machine language instruction. If that instruction at location 385 indicates that the contents of memory location 1376 should be added to the contents of memory location 2795, then the CPU will treat the values in those memory locations as numbers.

A major distinction between different programming languages is the set of resources provided by that language for interpreting the values stored in the computer’s memory. The different mechanisms provided by the language are generally referred to as the language’s data types.

The simplest data type supported by virtually all programming languages is the numeric data type. Just like we recognize two kinds of numbers, whole numbers and fractions, computers normally distinguish between int, or whole number values, and float, or fractional values. Technically, a float value is actually like a decimal representation of a fraction. And just like some fractional values, like 1/3, don’t have an exact decimal representation, many float values are actually approximations for the fractional value that is being represented.

In practice, we will use an int when storing a whole number such as a person’s age (i.e., 19) or golf score (i.e., 97). Float is short for floating point number and can stores things like a grade point average (i.e., 3.48) or a bank account balance (i.e., 578.25).

As a programmer, you have to decide on the data type as you anticipate how your data will processed and viewed. For example, maybe you are writing software that will ask the user to enter today’s temperature in Fahrenheit degrees. If you expect all input values to be whole numbers (i.e., 72), then you would choose an int. If a user is allowed to enter numbers with decimals (i.e., 68.45), then a float would be the proper data type.

Numeric Operators

As you begin to solve problems, you will use numeric operators to create formulas. The next table shows some of Python’s most common numeric operators.

OperationOperatorPython ExampleResult
Addition+3+58
Subtraction14-95
Multiplication*4*728
Floating point division/19/44.75
Integer (floor) division//19//44
Remainder (modulus)%19%43
Exponent**2**532
Table 3.1: Python operators.

Precedence Rules

Suppose a student decided to use Python in the interactive mode to find her average of three exam scores: 70, 80, and 90. When she typed in the expression, the result is shown below:

Of course, that doesn’t seem right. There is a good chance you already figured out the problem. The precedence rules (order of operations) you learned in your math courses apply in Python expressions.

The precedence rules follow this order:

  1. Parenthesis
  2. Exponent
  3. Multiplication and division (left to right)
  4. Addition and subtraction (left to right)

The student’s expression had two additions and a division. Since division has a higher precedence than addition, 90 was divided by 3 first. That quotient was then added to 70 and 80, resulting in the 180. To force the addition to occur first, we would need to add parenthesis since they have the highest precedent level:

When we write programs, we usually want to store or save results of expression so that we can later use them or display them. To store data, we use a variable, which is simply a named memory location. Python has rules for creating variable names.

Rules for creating variable names:

  • Use letters, digits, and underscores
  • Variable names are case-sensitive
  • Do not use reserved words

A good practice for creating a variable is to use meaningful names like hoursWorked, firstName, and exam3. The table below provides a list of potential variable names.

Variable nameValid name?Comments
CityyesThis is a good name
cityyesGood name, too, but it is a different variable than City
printnoprint is a Python function
PrintyesIt is valid, but may be confused with print
Hours-workednoThe dash (-) is not a valid character
Hours_workedyesThis is a good name
wyesIt is valid, but 1-letter names should be avoided
mphyesValid, but milesPerHour would be much better
inputnoinput is a Python function
last namenoYou can’t have spaces in a variable name
Table 3.2: Python variable names.

Variable Assignment

To give a value to a variable you use an assignment statement. The assignment operator is the equal sign (=). The instruction age = 19 will assign the value 19 to the variable age. Technically, age is a reference that identifies the memory location where your program stored the number 19. You might picture your computer’s memory as a bunch of cells:

Perhaps later you decide to change the value of age, setting it to 23 with the instruction age = 23. The age variable now points to the number 23 in memory. (Side note: The number 19 is now orphaned and will be removed by garbage collection.) Your computer’s memory will look like this:

Once you assign a value to a variable, you can retrieve it to use in another formula or you may want to output it using the print function. It’s recommended that you use the interactive mode to experiment with assigning and printing variables. Here are a couple of examples:

Figure 3.1: Examples of the Python assignment operator.

Error Types

You noticed in that last example that a message popped up. Errors show up in red when you work in Idle, so we try to avoid that color. In this example, we tried to print the contents of a variable named temp, but we never created or defined that variable. Python will not permit you to access a variable if you haven’t defined it.

Every language has its own syntax, which are the rules of language. This includes the language structure, whitespace, reserved words, etc. If one of your instructions breaks one of these language rules, it is called a syntax error. Unfortunately, many beginning programmers (as well as some experienced programmers) mistakenly believe that, once they have removed all syntax errors, their programmers are good to go. The table below shows three types of common programming errors. A runtime error, such as dividing by zero or taking the square root of a negative number, occur during program execution. With a logical error, your program runs but the intended results or outputs are not correct.

Type of ErrorDescriptionExamples
SyntaxAn instruction breaks the rules of the languageprint(5   number1+number2=total
RuntimeThe given data causes a problem while your program is runningprint(10/0)   math.sqrt(-25)
LogicYour program still runs, but the results are not correctAvg=exam1+exam2+exam3 / 3   triangleArea=base*height*2
Table 3.3: Programming Error Types.

Common Python Functions

As we continue to solve problems using Python, more functions will be needed to perform necessary commands. The table below lists a couple more common Python functions along with examples of each in action:

FunctionPython ExamplesResult
Absolute valueabs(-23)   abs(5.8)23   5.8
int conversionint(3.8)   int(“47”)3   47
float conversionfloat(5)   float(“-29.3”)5.0   -29.3
round  round(23.7)   round(-5.2394)   round(4.7777,1)   round(34.88888,2)24   -5   4.8   34.89
Table 3.4: Common Python Functions.

INTERACTIVE – Debugging

Often times, we describe an error in a computer program as a bug. The process of removing those errors is therefore called debugging. To give you a little practice debugging, consider the program below. It is trying to compute and display the hypotenuse of a right triangle given the two triangle legs inputted by the user. There are several errors embedded in this program, though. See if you can identify and correct each error. If you are familiar with a 3-4-5 triangle, that would be an easy case for you to test. To begin, try simply running the program and see what clues that gives you.

Some Example Applications

Let’s take a look at a couple of examples to see if we can tie it all together. First, we will develop a program to compute the winning percentage for a baseball team. The problem-solving in this example is pretty straight-forward. As you can see from the comments, the program is broken into input, processing, and output sections. The team wins and losses must be converted to integers since the input function returns a string. You might also notice that we included the round function to display the winning percentage to the nearest tenth.

Figure 3.2: Baseball Winning Percentage Program.

Here is a sample run of this program. Notice that the program output is displayed as blue, and the user input is shown in black.

You may be curious as to when we would ever need the “%” or “//” operators. It turns out that they come in handy solving many problems. Suppose you worked as a cashier at a store, and you wanted to write a Python program to compute and display change for a customer. We will first show you some code that will solve this problem. Then, we will take a look at a sample run to help you understand how these two numeric operators are used.

Figure 3.3: Money Changing Program.

In the sample run below, the user input 68 as the number of cents the customer should be given. If you look at 68//25, the integer division returns 2 as the number of quarters. The expression 68%25 results in 18 as the remainder. Once the program computes the quarters, it next computes dimes in a similar fashion. The expression 18//10 results in 1 dime and the remainder 18%10 is 8. The number of nickels is 8//5, or 1. Finally, the number of pennies is 8%5, or 3.

Chapter Review Exercises:

3.1. Show the output of the Python code.

a = 18 – 3 * 4 + 7

print (a)

3.2. Show the output of the Python code.

b = 9/5

print (b)

3.3. Show the output of the Python code.

c = 9//5

print (c)

3.4. Show the output of the Python code.

d = 17%3

print (d)

3.5. Show the output of the Python code.

e = 4**3

print (e)

Programming Projects:

3.1. If P dollars (called the principal) is invested at r% interested compounded annually, then the future value of the investment after n years is given by the formula:

Write a program to ask the user for the principal, annual interest rate given as a percentage, and the number of years of an investment. Compute the future value and display it using 2 decimals. Also, compute the total interest earned on the investment and display that value using 2 decimals.

3.2. Suppose you held a garage sale and were wondering how much money you brought in from the paper money. Think about designing a solution that would ask the user to enter the number of bills of each type (1-dollar, 5-dollar, 10-dollar, and 20-dollar) that he possesses. Then, it would compute the total amount of money from the garage sale and output it.

  • 1) Write an algorithm to solve the problem. Save it as a Word document.
  • 2) Draw a flowchart to model the solution to the problem. Save it as a PDF document.
  • 3) Implement the solution to your problem as a Python program. Add 4 lines of comments at the top.