Basic Data Types

Note

Learning objectives: Identify the number, letter, and Boolean data types. Predict the outcomes of arithmetic operations on basic data types. Understand coercion and Boolean evaluation. Read an unfamiliar program and predict what it does.

  • We can assign any data to a variable, just like assigning x=2 in your math class.

  • Let’s make one called myspecialvariable. (That’s a great name. I must be awesome.)

>>> myspecialvariable = 4
>>> myspecialvariable
4
>>> myspecialvariable + 5
9
>>> type(myspecialvariable)
<class 'int'>
  • Notice that last command asked Python what type of variable I had. Python said it was an int or an “integer.”

  • That’s a basic data type.

  • Oh, look: the page title says Basic Data Types. I wonder if that’s a clue.

Number-ish data

  • All of these can be positive or negative.

Class Name

Common Name

Meaning

int

Integers

Whole, real counting numbers.

float

Floating point numbers

Real numbers that do not have to be whole.

complex

Complex numbers

Partly imaginary numbers. Save this for later.

Letter-ish data

  • Characters are visual representations stored as a code in a lookup table called a “code page.”

  • A long time ago, we had a lookup table called EBCDIC. It was dumb. (That’s a documented fact. Just ask your parents.)

  • Then, we had ASCII. That’s closer to modern, but does not include many modern letters.

  • For real work, we use a standard called Unicode, which is not dumb at all.
    • It includes ASCII as a starting point but is expandable and includes non-English letters and, unfortunately, Emoji.

    • It will soon support Elvish and Klingon as international alphabets.
      • This knowledge will not help you get into a good high school.

      • Do not mention it in interviews.

  • In Python 3, all letter-ish data is string.

  • Anything you put in…
    • single-quotes, such as ‘my string’;

    • quotes, such as “my string”;

    • or triple quotes, such as “””My triple-quoted string is cooler than yours.”””

    • …becomes a string.

Class Name

Common Name

Meaning

str

String

Representations of text.

Truth-ish data

  • This is also called Boolean data, meaning it is True or False.

  • All sorts of things can represent truth or falsehood. Empty values are always false.

  • Non-empty values are always true, even the negative ones.

Example value

What it means

Boolean value

False

Boolean false value

False (duh)

True

Boolean true value

True (still duh)

0

The int zero

False

-50.0

The float -50.0

True

‘’

Empty string

False

None

A special none-type

False

Class Name

Common Name

Meaning

bool

Boolean

Truth or falsehood.

>>> False               # Python still returns the value of whatever you type.
False
>>> True
True
>>> True + True         # Booleans are also integers when we treat them like integers.  This is (1 + 1).
2
>>> True + False        # This is (1 + 0).
1
>>> False - True        # This is (0 - 1).
-1
>>> True or False       # This checks if you have at least one True in your tested criteria.
True
>>> True and False      # True and False cannot be True because something in your set is False.
False
>>> False and False     # False and False produces False.
False
>>> not True            # Go figure.
False
>>> not False           # Not-False isn't "kinda true."  Computers are rarely wishy-washy.
True
>>> not (True or False) # Parentheses work for Booleans, too.
False

Putting it together

  • What do you think will be the result of the following operations?

  • What data type will the result have?

>>> 7 - 5          # You better get this right.

>>> 17.0 / 3       # This is trickier.

>>> '5.0' + '7.0'  # Pay close attention.  This may not be obvious.

>>> 17 % 3         # Remainders, remember?

>>> '40' * 3       # This will blow your mind.  Maybe not.  It's weird, though.

>>> '40' + 3       # The computer will pass judgment on you for typing this.

Coercion

  • To coerce is to make someone do something, often by force or threats of force.

  • In Python, the programmer is the bully and bullying is encouraged.

  • Using the name of the data type as a function name, we can transform one data type into another.

  • A “function,” which we will discuss more later, is like a tool or what you would think of as a command.

    • For example, the result of the function sandwich() with the parameters pb and j should be my lunch.

>>> pb = 'peanut butter'
>>> j = 'jelly'
>>> def sandwich(ingredient_one, ingredient_two):
...   print('Here is your ' + ingredient_one + ' and ' + ingredient_two + ' sandwich.')
>>> sandwich(pb, j)
'Here is your peanut butter and jelly sandwich.'
  • Using def, I can make my own functions, but Python already defines functions like int() and str() for me.

Let’s do some coercing.

>>> type(5.0)                   # This just tells you the type of value you have.

>>> int(5.0)                    # Our first coercion.  What type did it return?  How can you tell?

>>> myspecialvariable = 5.0     # We assign myspecialvariable to be 5.0.
>>> type(myspecialvariable)     # Now, we ask what type of data is myspecialvariable.

>>> int(myspecialvariable)      # Now, we coerce the value to be an integer.

>>> type(myspecialvariable)     # Someone always gets ths wrong, as you are smart; the computer isn't.

>>> myspecialvariable = int(myspecialvariable) # Now, it will do what you expected.

>>> type(myspecialvariable)     # See?

>>> type(int(5.0))              # This should be more clear, but you have to think like a computer.

>>> str(8)                      # So...um...yup...this works.

>>> int(44.12)                  # This is not rounding!  You just think it is!

>>> int(44.92)                  # Again, see?  Not rounding.  We're coercing.

>>> int('44.12')                # ...but...but...why, Python?  Why?

>>> int('44', 8)                # I made 36 out of 44!  (No, I didn't.  What happened here?)

>>> float('50')                 # Why do we want to do this?  Can you think of a reason?

>>> float('fifty')              # How clever is the Python community?  Not clever enough, apparently.

>>> bool(0)                     # Remember this from a few minutes ago?

>>> bool('squirrel')            # Squirrel!

>>> bool(-1)                    # Like squirrels, negative numbers indicate truth.

>>> int(True)                   # Can you guess what happens here?

>>> int(False)                  # ....or here?

Sample program and closing thoughts

  • This uses conditionals called while and if, which we will cover in detail later.

  • They do exactly what you think they should, so just follow along and let’s figure out what the computer does.

  • In Python, spaces matter. When you indent a line, it becomes part of a stanza or paragraph under the previous, less-indented line.

A program! … even though you aren’t ready to write this yourself…yet.
 1# Notice the Boolean here.  The "while True" means run forever!  Forever!
 2while True:
 3    # input() gets input from the user and returns what the user wrote.
 4    your_age = input('How old are you? ')
 5    # If your_age evaluates to True, meaning it's not empty or zero...
 6    if your_age:
 7        # We will cover "try" later.  Python will run code and if it cannot handle it, it will throw an exception.
 8        try:
 9            birth_year = 2019 - int(your_age)
10            print('If you are ' + your_age + ' then you were born in or before ' + str(birth_year) + '.')
11        # If it reaches the exception (meaning it got an error in the "try" stanza, do this...
12        except:
13            print('Fool!  You did not type a number.  I cannot change ' + your_age + ' into an integer.')
14    # When Python gets to this line, it goes back to the top of the "while" statement and starts again.
  • Now, let’s take this apart and practice.

  • Play with Python at home. Ask your parents’ permission to install it at home.
    • If you cannot, I can provide you with an online practice space.

    • Computer science is a branch of math and math takes practice.

    • When next we meet, we will cover branching and looping, and write our own functions.