Computers can keep track of all sorts of information, but a good way to classify the basic data types are into numeric and non-numeric data.
SubsectionA.2.1Numerical data types
In mathematics prior to Calculus, the basic type of things you study are numbers, pretty vaguely defined, and then in calculus you’re introduced to the idea of sets of numbers:
\begin{align*}
\amp\Nats = \set{0,1,2,3,\dotsc},\\
\amp\Ints = \set{\dotsc,-2,-1,0,1,2,\dotsc},\\
\amp\Rats = \set{p/q:p,q\in\Ints,q\neq 0},\\
\amp\Reals,{}\text{ the set of all real numbers},\\
\amp\Comps = \set{a+ib:a,b\in\Reals, i^2=-1}.
\end{align*}
Mathematically, there are certain actions which can be taken using all of these numbers: your basic algebraic operations, with a few notable exceptions. The idea that different kinds of number can have different kinds of properties is the essence of the programming data type. The first and easiest data type to work with in Python is the int type, and the easiest way to start working with ints is to assign one to a name.
TechnologyA.2.1.The help command.
When working in Python, if you’re not sure what to do next, you can access Python’s built-in help menu from the console.
>>> help()
Welcome to Python 3.8's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.8/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
help>
You should freely use help as often as you want.
Data types matter in programming because computers are brainless machines. This is why syntax matters: the computer needs to know what a thing is to know what to do with it. Mathematically, if we read \(x+5 = y\) then we assume that both \(x\) and \(y\) are things for which the expression is sensible, but that is due to years of learning mathematical syntax.
TechnologyA.2.2.Assignment vs. equality.
Generally speaking, programming languages use a different syntax for the declarative statement “Let \(x\) take the value 3” than they do for the question “Is \(x\) equal to 3?” Mathematicians do not, relying on the surrounding context to determine what is meant by \(x=3\text{.}\)
To assign the value 3 to the variable named \(x\) in python, we use x = 3. To inquire whether or not the variable named \(x\) is equal to 3, we use x == 3. The spaces around the operators = and == are conventional and help make readable code.
>>> x = 3
>>> x == 3
True
>>> y == 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
ListingA.2.3.Assignment vs. equality
ObservationA.2.4.Assignment produces no output.
A statement like x = 3 in Python never produces output. To see the value of the variable named x, use print(x).
All of the common mathematical operations are defined in Python, with only two slightly strange behaviors:
TableA.2.5.Arithmetic operators in Python
Operation
Implementation
Addition
a + b
Multiplication
a * b
Subtraction
a - b
Floating Point Division
a / b
Integer Quotient
a // b
Integer Remainder
a % b
Powers
a ** b
You might wonder what floating point division is and how it differs from normal division. The difficulty with division on a computer is that not every real number can exactly be represented in computer memory with . For a full explanation of this, see the official IEEE Standard 754 for Floating-Point Arithmetic 10
. In any case, the Python operation a / b produces the floating point approximation of \(a/b\) rather than the exact value, even when \(a\) and \(b\) are integer powers of 2.
The convention that a ** b (rather than a ^ b) represents \(a^b\) is the deliberate choice of the developer of Python, allowing a ^ b to represent the bitwise XOR operation. Beginning programmers don’t usually need bitwise XOR.
To use more math functions than these, Python includes a standard math package. To include it, add import math to the beginning of a module, then access the functions inside the math library by using math.sqrt(...) and so on.
TechnologyA.2.6.Loading additional packages.
Python comes preinstalled with many useful packages, loaded using the import command.
>>> import math
>>> math.sqrt(15)
3.872983346207417
ListingA.2.7.Using the import math command
The use of dot notation to access functions within a module is standard within Python and will be used extensively.
SubsectionA.2.2Non-numeric data types
The two most useful non-numeric data types are Boolean values of True and False (stored in thebool data type) and strings, which encompass every sequence of printable or non-printable character. Strings have data type str.
SubsubsectionA.2.2.1Boolean variables
The Boolean values of True and False are fundamental to logical conversation and do not need much explanation. However, the laws of logic allow many operations to combine Boolean values in interesting ways.
TableA.2.8.Logical Operators
Name
Operator
Conjunction
and
Disjunction
or
Negation
not
To really understand what the logical operators do, let’s look at a truth table where the values of variables p and q take the various possible combinations of True and False.
TableA.2.9.Truth table for the basic logical operators of and, or, and not.
p
q
p and q
p or q
not p
False
False
False
False
True
False
True
False
True
True
True
False
False
True
False
True
True
True
True
False
TechnologyA.2.10.Type conversion.
In Python, True and False are actually integer values. You can always attempt to convert one data type into another by using the name of the target data type like a function.
>>> int(False)
0
>>> int(True)
1
ListingA.2.11.Integer values of the bool values
Converting one data type into another this way is called type conversion or type casting.
Boolean data types are used extensively to control the flow of execution of an algorithm, as can be seen in Algorithm 1.1.5 and later in Subsection A.5.2.
SubsubsectionA.2.2.2Strings
A finite sequence of symbols enclosed in matching single or double quotes is a string, represented by the str data type.
TechnologyA.2.12.Valid strings.
There are many different valid combinations of quotes which can enclose a string.
>>> 'Single quotes may enclose a string'
'Single quotes may enclose a string'
>>> "Double quotes may enclose a string"
'Double quotes may enclose a string'
>>> '''Multiline strings
... may be enclosed in three single quotes'''
'Multiline strings\nmay be enclosed in three single quotes'
>>> """Alternately, they may
... be enclosed in three double quotes."""
'Alternately, they may\nbe enclosed in three double quotes.'
>>> '"Quotes may be mixed," said he, "but I may not quote nor contract."'
'"Quotes may be mixed," said he, "but I may not quote nor contract."'
>>> "They've been reversed here."
"They've been reversed here."
>>> print("This isn't the best example.\n\t- Dr. Graves")
This isn't the best example.
- Dr. Graves
ListingA.2.13.Valid input strings
As can be seen above, Python uses single quotes internally. Also the line break character is changed to \n for internal storage. This is called an escape character, and there are several: \', \", \n, \t, and \\, among them.
To see a str in its proper form, with all escape characters replaced with the correct output, we use the print(...) function, as shown above.
There are many other things one can do with strings, since the str class comes equipped with many interesting attributes and methods, but those topics are best saved for later.
TechnologyA.2.14.Formatted strings.
The one additional feature of strings that can be used early and to great gain is the ability to modify strings for output based upon string formatting. There are several ways to do this:
printf-style String Formatting is named after the printf command for the C/C++ programming languages. In this mode, certain percent-codes (such as %s, %d, and %f) can be included in a string and then replaced via the % operator.
The String Format Method allows keywords enclosed in curly brackets (like {keyword}) to be replaced as arguments to the str.format(...) method.
Formatted string literals allow a string to be defined similarly to the string format method, but using Python evaluation within the string.
First see a demonstration of the % operator for strings.
>>> print("""This %s contains several (%d) percent codes,
... which are replaced (%f) by using the percent operator.
... """ % ('string', 3, 3.15926535) )
This string contains several (3) percent codes,
which are replaced (3.159265) by using the percent operator.
ListingA.2.15.Changing a string using the % operator
Next consider an example of the use of the str.format(...) method.
>>> print("""A similar {a} which has {num} replacements.
... Notice that the {lcb}...{rcb} keywords can be replaced
... by any value whatsoever.""".format(a='StRiNg', num=7.31,
... lcb="{", rcb="}") )
A similar StRiNg which has 7.31 replacements.
Notice that the {...} keywords can be replaced
by any value whatsoever.
ListingA.2.16.The str.format method
Finally, the method using f-strings.
>>> name = "Bob the Tomato"
>>> multiplicity = 5
>>> out = f"{name} can be copied {multiplicity} times: {multiplicity*name}"
>>> name = "Larry the Cucumber"
$ multiplicity = 2
>>> print(out)
Bob the Tomato can be copied 5 times: Bob the TomatoBob the TomatoBob the TomatoBob the TomatoBob the Tomato
ListingA.2.17.Formatted string literals, called fstrings
Note in this last example that the value of the fstring out is not changed even when the values associated with the names used to construct out changed.