Data Types
Last updated
Last updated
A data type is simply the type of data we can store in programs. Python has a fairly small set of data types.
integer (int) which are numbers like 1
, 4
, 7
floating point (float) which are numbers like 3.5
, 6.2
, 8.9
string (str) which is simply a collection of characters (any character you
wish like: askj#@lk14p
) surrounded by quotes (' or ")
boolean (bool) which can be either True
or False
(see [George
Boole](https://en.wikipedia.org/wiki/George_Boole)). True
and False
are
special words in Python and are reserved for their raw values. That means
that you may not use them when naming things.
You can manipulate data using operators (+, -, *, /, <, >, etc). The obvious math operations like 1+2
work but we also have other operations like 'I like ' + 'britney'
. This operation will concatenate (or combine) the two strings into a single string.
Try printing out to the terminal screen some math operations:
Running this program should produce: 8
and reed likes to program
.
In addition to the math operators and a few that work on strings there are also a number of booleans operators (<, >, <=,
=, ==, !=, not, or, and).
Running this program should produce: True
4 times.
Try printing out some expressions using various operators!
Variables are simply a way to keep track of the values you want to manipulate. They act as boxes to hold data types. You can create a variable by doing the following:
The first variable will hold a string with the value of reed
, the second will hold an floating point with the value of 70.9375
, and the third will hold a boolean with the value of True
.
Variable names have specific rules. They have to be a single word (no spaces) and can have numbers, letters or underscores. They cannot begin with a number and are case sensitive (meaning SPAM
does not equal spam
).
Try storing the results of your previous operations in variables. Then print them out!
You can combine strings (concatenate) using the +
operator but this gets pretty inefficient if you do it in loops (which we will learn about in a later lesson). It is always a good idea to combine strings using string formatting. You can create a string that has special tokens inside of it and then replace those tokens with the values you supply.
Doing this will be more efficient and ends up being more readable in my opinion. One thing to keep in mind though is that if you have a decimal number (like height
in the example), you need to use a %d
instead of a %s
. For a list of format characters and what they mean check out the Python documentation. Dive Into Python also has a really great article that goes into greater detail.