Chapter 2, Lesson 2 Text

Chapter Two: Working with Data

Lesson Two: Using Numeric Variables

 

There are two main types of numeric data: integers and floating-point numbers. When you assign a numeric value to a variable, the variable will automatically become an integer or floating-point data type, depending on the type of value you assign.

Integers

Integers are positive or negative whole numbers, including the number zero (0). Sometimes an integer is also called an "int" for short. There are no fractions or decimal places in an integer value. Here are some example values that can be stored as integers. 

  • A student’s grade level (such as 12)
  • The number of brothers and sisters you have (such as 2)
  • The year you were born (such as 2005)
When writing numeric values in Python code, do not use commas or other separators. A number that you might hand-write as "3,482" on paper should be typed as "3482" in your source code.

The print() function knows how to display an integer on the screen, so you could pass a hard-coded or typed-in number directly to the function. Run the example code below to see the output. Then, change the integer value to something different and try running it again.

Try It Now

 

Anywhere that you might use a hard-coded value like "45", you can also use a variable of the same type. Let's create an integer variable named myScore and assign a value to it, Then, we'll pass that integer variable into the print() function to see the results on the screen. Try it yourself!

Try It Now

 

Floating-Point Numbers

floating-point values are real numbers, which are numbers that can contain an integer plus a fractional part, separated by a decimal point. Sometimes a floating-point number is also called a "float" for short. Do you see how each of the following examples should be stored in a floating-point variable?

  • The math constant PI (3.14159)
  • Your grade point average (3.5)
  • The amount of money in your pocket ($0.75). 

floating-point values are not required to have a fractional part. The digits to the right of the decimal point may all be zero (4.00). 

Just like integers, floating-point numbers should not include commas or other symbols like dollar signs. You should only use numbers and decimal points. So, the hand-written value "$1,000.50" would be written as "1000.50" in Python code.

The print() function knows how to display floating-point values, just like integers. Experiment with the following code example to see how it works.

Try It Now

 

Creating a floating-point variable and using it in place of a hard-coded value works the same way. Run the code below to create a floating-point variable named PI, store a value in it, and then print the contents of that variable to the screen.

Try It Now

The Python language will automatically choose the correct numeric data type based on the number that you enter in your program. Python will consider any number written without decimals as an integer (like 1000) and any number written with decimals as a floating-point (like 3.14).

The type() Function

You may want to study the data type of a particular variable to see if it is an integer, floating-point or some other type. Python contains the built-in type() function that will give us this information. type() accepts a variable name between the parentheses and will return a description of the data type as a string.

In the example below, we create a floating-point variable called myValue. We then pass that variable into the type() function and store the resulting type information in another variable called myType. Finally, we print the contents of myType so we can see what information was returned. Try it yourself and see the results! Then, change the input value from 3.14 to 0 and run it again.

Try It Now

 

It is OK to pass the results from one function directly into another function. So, we could take the string results from type() and pass that directly into the print() function as shown below.

Try It Now

 

You will find that floating-point variables have a type of "<class 'float'>" and integers are described as "<class 'int'>". If you use other data types like strings, you will get similar descriptions like "<class 'str'>". We'll use the type() function in a moment to help understand the results of mathematical operations.

Math Operations

You can do basic mathematic functions like additionsubtractionmultiplication and division on your numeric variables. You can also get the remainder or modulus of a division operation. Python (and most other programming languages) uses the following special characters to perform the math operations:

SymbolDescriptionExample StatementmyResult
+AdditionmyResult = 1 + 23
-SubtractionmyResult = 5 - 32
*MultiplicationmyResult = 4 * 28
/DivisionmyResult = 10 / 52
%ModulusmyResult = 10 % 31

 

mathematical expression is formed by writing two numeric values, separated by one of the mathematical symbols +, -, *, / or %. Python will perform the calculation, and then you will most likely want to store the result in a variable, print the result to the screen, or put it to some other use.

Python will automatically examine the data types of your input values and produce a result of the correct data type. So, adding together two integers will produce an integer result, while subtracting two floating-point values will give you a floating-point result. The results of a division operation (/) are always floating-point, even if the answer itself (like 8 / 2 = 4) is a whole number.

The examples below demonstrate using a mathematical expression directly as input to a function like print() as well as storing an expression results in a variable for future use. Try changing each math expression to experiment with all four operations (+, -, * and /). Run the code to see your results!

Try It Now

 

The forward slash (“/”) is used to divide one value with another. The left value is the dividend (the number on top that gets divided) and the right number is the divisor (number on bottom that is doing the division). Be sure that you never attempt to divide by 0, or you will receive an error when you run your program. Modify one of the expressions above to divide by 0 and look for the resulting error message.

For example, if you attempt to divide "5 / 0", you will see an error message like the one below.

Traceback (most recent call last):
  File "code1.py", line 1, in <module>
    print(5 / 0)      # print math result directly to the screen
ZeroDivisionError: division by zero
Most Python error messages are very helpful, showing you the exact file and line number where the error happened, the statement that caused the error, and a description of the error (e.g. "division by zero"). When you see an error like this, use the information it contains to find and fix the problem in your code.

Longer Expressions

You can chain together several math operations into one statement. Simply continue to add additional symbols and input values to the right of the first operation. For example, you can multiply together 4 numbers by writing the following expression.

Try It Now

 

We will discuss longer expressions in more detail in a later chapter.

Using Variables in Math Expressions

Writing hard-coded math expressions like "5 + 1" in your code is not very interesting, because the result will always be the same. Programmers will often use variables in place of one or both input values to a math expression. If you have two input values stored in variables score1 and score2, then you could write an expression to add those inputs together and store the result in a third variable.

Run the example below to see the results. Do you see how we are using variables as parts of mathematical expressions?

Try It Now

 

Work with Me: Math Lab - Triangles

 

In this exercise, you are going to create numeric variables and use them in a mathematical expression to calculate the area of a triangle. The area of a triangle is equal to one half of the base multiplied by the height, or area = 0.5 * base * height.

The starting code below contains comments that ask you to write specific code on each line following the comment. Add your code in the areas shown and then click "Run Code" to verify your results.

Try It Now

  

 

The calculated area using a base of 10 and a height of 5.0 should be 25.0. The base variable is an integer, while the height and area variables are floating-point. Try changing the initial base and height values and confirm the new area is calculated correctly.

Remember, if you need to start over, you can go back to the default code by reloading this page in your web browser.

End of Lesson


Last modified: Wednesday, 8 May 2019, 7:59 AM