Numeric Data Types¶
Every variable in Python has a “type”. The type of a variable is based on the contents of that variable, and determines the ways in which that variable can be used. For example, we cannot perform certain operations on variables of certain types.
We will begin our discussion of data types with the data types intended to hold numbers. Python has three numerical variable types: int
, float
, and complex
. In this class, we will work only with the int
and float
variables.
An
int
variable is used to represent an integer.A
float
variable is used to represent a decimal number.
We will discuss the importance of variable types in more depth later. For now, we will show how to determine a variable’s type using the type()
function.
x = 7
type(x)
int
y = 3.7
type(y)
float
Python infers whether a numeric variable should be stored as an int
or a float
based on the value of that variable. Occasionally we might wish to assign a whole number value to a variable, but have it actually stored as a float. We can accomplish this by adding “.0” to the end of the number.
z = 14.0
type(z)
float
Operations Combining Floats and Ints¶
The sum of an int and a float is always stored as a float.
print(x)
print(y)
u = x + y
print(u)
print(type(u))
7
3.7
10.7
<class 'float'>
print(x)
print(z)
v = x + z
print(v)
print(type(v))
7
14.0
21.0
<class 'float'>
The ratio of any combination of ints and floats is always stored as a float.
a = 7
b = 5
q = a / b
print(q)
print(type(q))
1.4
<class 'float'>
c = 20
d = 4
p = c / d
print(p)
print(type(p))
5.0
<class 'float'>
Rounding¶
If we wish to round a float
value, we can do so using the round()
function. The syntax for round()
is as follows: If we wish to round the value number
to a number of decimal places indicated by digits
, we could use the command round(number, digits)
.
Some examples of the round()
function are provided below.
print(round(3.14159, 0))
print(round(3.14159, 1))
print(round(3.14159, 2))
print(round(3.14159, 3))
print(round(3.14159, 4))
3.0
3.1
3.14
3.142
3.1416
If we do not provide round()
with the desired number of digits, writing only round(number)
, then Python will round the number to the nearest integer.
print(round(12.3))
print(round(12.7))
12
13