Data Types#

Learning Objectives#

  • List the four basic data types in Python (int, float, str, and bool).
  • Give an example value for each data type. For bool, list all possible values.
  • For each data type, write a line of Python code that creates a variable that stores a value with the data type.
  • Create an empty string.
  • Determine the type of a value or variable.
  • Convert a variable from one data type to another. If the conversion is not possible, state why.

Overview of Data Types#

Variables are containers for data. Each piece of data is classified by the computer as having a data type. This is true for programming languages, such as Python. It is also true in Excel! Every cell in an Excel worksheet has a value, and this value has a data type.

Python has many data types. For now, let’s learn about a few of Python’s basic data types. Later, you will see how these basic data types are grouped together to form more complex data structures.

Some basic data types in Python are:

Data Type

Description

int

int stands for integer. These are whole numbers and they can be positive or negative.

float

float stands for “floating point number”. These are numbers that can contain a fractional amount, such as 3.14.

str

str stands for “string”. These are textual values.

bool

bool stands for boolean. These can have a value of either True or False. They are named after the mathematician George Boole.

There are many other data types in Python, but let’s focus on these simple data types for now. We will discuss other data types later in this course.

Integers (int data type)#

An integer is a positive or negative whole number. To create an integer value, simply enter a whole number into a cell or assign it to a variable.

# Remember that anything after a '#' symbol is a comment.
# This cell creates an integer value, 7, and then does nothing with it.
7
7
# This cell assigns the integer value 7 to a variable k
k = 7

If you open the variable inspector, you will see that k was added to your environment, that it’s holding an int, and its value is 7.

Common error made by accountants: entering commas and dollar signs!!!#

Let’s face it. We’re accounting nerds. And when we work with large numbers, we like to use commas, right? Have you ever seen a financial statement that showed something like this:

Revenue (in millions): 13962

We hope not because that is poorly formatted. No, as good accountants, we would write:

Revenue (in millions): $13,962

Do not use dollar signs and commas to create numbers in Python! It will result in errors.

# Example of an error created by using commas
revenue = 13,962
print(revenue)
(13, 962)

When you run the above cell, you will not see an error. The problem is much more insidious. You just created a “tuple”, or collection of data. Python created a variable, revenue, that is a collection of two numbers, 13 and 962! That’s probably not what you wanted.

# Example of an error created by using a dollar sign
revenue = $13962
  Cell In[4], line 2
    revenue = $13962
              ^
SyntaxError: invalid syntax

Common error made by accountants: entering parentheses for negative numbers!!!#

Accountants write negative numbers using parentheses. Do not use parentheses to enter negative numbers when programming! Simply enter a negative sign before the number. As you will see later, parentheses are used to group operations.

# This will NOT create a negative number.
profit = (109.27)
print(profit)
109.27
# Enter negative numbers this way:
profit = -109.27

# You can still print out numbers as accountants would.
# This code uses Python's built-in absolute value function.
# Don't worry if you do not understand this print statement. We will
# cover it later.
if (profit < 0):
    print(f'I lost $({abs(profit)})!')
I lost $(109.27)!

Floating Point Numbers (float data type)#

A float is a number that can contain a fractional amount, such as 5.7. To create a float, enter a number with a decimal. The following code creates three variables, each holding a floating point number.

myFloat1 = -5.7
myFloat2 = 5.0
myFloat3 = 5.

If you run the code above and open the variable inspector, you will see that myFloat1, myFloat2, and myFloat3 were added to your environment. All three are holding a float, and their values are -5.7, 5.0, and 5.0, respectively.

Notice that we can force Python to treat 5 as a floating point number by adding a decimal or a .0 after the 5. Without the trailing decimal point, Python would store that 5 as an integer.

Common error made by accountants: entering commas, dollar signs, and parentheses!!!#

See above. We repeat: Do not use commas, dollar signs, and parentheses to create numbers in Python!

Strings (str data type)#

In Python, textual data is stored as a string (str). To create a new string, enter text inside quotes. You can use single quotes (’) or double quotes (“). For example:

s1 = 'Welcome to ACCY 570!'
s2 = "157"

You’re probably wondering why you can use either single- or double-quotes. The reason is so that you can include quotes in your string!! For example, consider the following:

myString = 'Professor Mendoza said, "Burger King is my favorite restaurant."'
print(myString)
Professor Mendoza said, "Burger King is my favorite restaurant."

By using single-quotes to enclose the string value, we are able to include double-quotes in the string. We could instead use double-quotes to delineate the string and include single quotes inside the string. For example:

myString = "Professor Herbold said, 'Burger King is good, but Wendy's is better.'"
print(myString)
Professor Herbold said, 'Burger King is good, but Wendy's is better.'

When Python sees a single quote, it looks for the next single quote. Everything in between the two single quotes is treated as a string. The same rule applies for double quotes.

Is it possible to include a single quote inside a single-quoted string? Is it possible to include a double quote inside a double-quoted string? Yes. You can do that with the backslash character ( \ ). When Python sees a backslash character, it treats the next character as a literal, meaning it does not assign a special meaning to it. Here are some examples:

myString = 'Professor Mendoza likes McDonald\'s.'
print(myString)

myString = "Professor Herbold said, \"I also like McDonald's, especially the Big Mac\"."
print(myString)
Professor Mendoza likes McDonald's.
Professor Herbold said, "I also like McDonald's, especially the Big Mac".

Empty strings#

Python allows you to represent an “empty string”. This is a string with zero characters. It is written as ‘’. Later, when you work with real data sets that contain text data, you will often see the empty string. It represents a missing or blank value.

Example:

myEmptyString = ''

Booleans (bool data type)#

Boolean values are very simple and very important. A Boolean (bool) can only assume the values True or False. You can either type those in, or you can run some code that results in a Boolean. Here are two examples:

myVar = True
myVar2 = False

The above code is really simple. It assigns the value True to myVar and the value False to myVar2. If you look in variable inspector, you will see that both of these variables have type bool.

Is5GreaterThan3 = 5 > 3
print(f'Is 5 greater than 3? {Is5GreaterThan3}')

Is9LessThan2 = 9 < 2
print(f'Is 9 less than 2? {Is9LessThan2}')
Is 5 greater than 3? True
Is 9 less than 2? False

The above code is more subtle. When Python sees the expression 5 > 3, it evaluates that expression. Since 5 is greater than 3, the expression evaluates to True. Python therefore assigns the value True to the variable Is5GreaterThan3. Similar reasoning applies to the second example.

Why Booleans are so important#

Boolean values are important because they are used in every conditional expression in Python! Whenever you write an if statement or while loop, you are using a Boolean value. For example, if you write:

if (x > 3):
    print('Something')
else:
    print('Something else')

Python checks whether x is greater than 3. If yes, then the value True is substituted for x > 3. If no, then the value False is substituted. In other words, it converts the expression (x > 3) into a Boolean value. In summary, every condition given to an if or to a while is converted into a Boolean.

Checking the type of a variable, value, or expression#

If you want to check the type of a variable, value, or expression, you can use the built-in function type(). This is best illustrated with examples.

type(7)
int
type(7.2)
float
type('0.625')
str
type(False)
bool
y = 'Hello there.'
type(y)
str
x = 3.1415
type(x > 2)
bool

Converting between types#

It is sometimes possible to convert a value of one type to a value of another type. Python provides built-in functions for this, and they follow certain rules. The functions are:

Function

Notes

int()

Attempts to convert its argument to an integer. If its argument is a float, it will truncate the fractional portion.

float()

Attempts to convert its argument to a floating point number.

str()

Attempts to convert its argument to a string.

bool()

Attempts to convert its argument to a Boolean value.

Notice that the word ‘attempts’ is used in the table above. Often, Python is able to figure out what you want, but sometimes it cannot. The following examples will show you valid and invalid conversions. They will also show you some common errors.

Converting to an integer#

# Convert from float to int. The fractional portion will be discarded.
int(3.7)
3
# Convert from str to int. This works if the string contains an integer.
int('-928')
-928
# Convert from str to int. This fails if the string contains anything other than an integer.
int('928 pigs')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[22], line 2
      1 # Convert from str to int. This fails if the string contains anything other than an integer.
----> 2 int('928 pigs')

ValueError: invalid literal for int() with base 10: '928 pigs'
# Convert from str to int. This fails if the string contains anything other than an integer.
int('928.3')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[23], line 2
      1 # Convert from str to int. This fails if the string contains anything other than an integer.
----> 2 int('928.3')

ValueError: invalid literal for int() with base 10: '928.3'
# Convert from bool to int. This will always work. True --> 1 and False --> 0
int(True)
1
# Convert from bool to int. This will always work. True --> 1 and False --> 0
int(False)
0

Converting to a float#

Converting to float are similar to converting to integers, you just use to float() function

Converting to a string#

This will always work with ints, floats, and bools. Later, when we learn about more complex types, the behavior of the str() function will be more complicated.

# Convert from int to str
str(17)
'17'
# Convert from float to str
str(17.8)
'17.8'
# Convert from bool to str
str(False)
'False'

Converting to a Boolean#

The general rule is that a numeric value of 0 (or 0.0) is converted to False. Any other numeric value is converted to True.

bool(-2.718)
True
bool(0)
False

The rule is that an empty string is converted to False, and any other string is converted to True.

bool('')
False
bool('False')
True
bool('The cow is white.')
True