3 Chapter 3: Numeric Data
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.
Operation | Operator | Python Example | Result |
Addition | + | 3+5 | 8 |
Subtraction | – | 14-9 | 5 |
Multiplication | * | 4*7 | 28 |
Floating point division | / | 19/4 | 4.75 |
Integer (floor) division | // | 19//4 | 4 |
Remainder (modulus) | % | 19%4 | 3 |
Exponent | ** | 2**5 | 32 |
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:
- Parenthesis
- Exponent
- Multiplication and division (left to right)
- 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 name | Valid name? | Comments |
City | yes | This is a good name |
city | yes | Good name, too, but it is a different variable than City |
no | print is a Python function | |
yes | It is valid, but may be confused with print | |
Hours-worked | no | The dash (-) is not a valid character |
Hours_worked | yes | This is a good name |
w | yes | It is valid, but 1-letter names should be avoided |
mph | yes | Valid, but milesPerHour would be much better |
input | no | input is a Python function |
last name | no | You can’t have spaces in a variable name |
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:
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 Error | Description | Examples |
Syntax | An instruction breaks the rules of the language | print(5 number1+number2=total |
Runtime | The given data causes a problem while your program is running | print(10/0) math.sqrt(-25) |
Logic | Your program still runs, but the results are not correct | Avg=exam1+exam2+exam3 / 3 triangleArea=base*height*2 |
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:
Function | Python Examples | Result |
Absolute value | abs(-23) abs(5.8) | 23 5.8 |
int conversion | int(3.8) int(“47”) | 3 47 |
float conversion | float(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 |
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.
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.
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.