The Very Basics: Numbers and Text
Contents
2. The Very Basics: Numbers and Text#
2.1. Lesson overview#
The creation, modification, and deletion of data lies at the heart of coding. This data, which is called an object in Python, can take the form of many things. An object can be a simple number, a logical true or false, a single text-based character, a combination of these, or even something more!
Definition: object
Individual data (e.g., the number 4, the word “dog”, an array of decimal numbers) is known as an object. Each data is its own object.
The type of data that an object represents (e.g., a number, a letter, etc.) is known as a class in Python. Each class will have certain functionality, requirements, or limitations tied to it, and can be expressed in different and unique ways.
Definition: class
The type of data that the object represents. There are many classes out there. You can even create your own classes in Python!
Therefore, it is important to understand some of the basic, built-in types of data (i.e., classes) that are available in Python standard library. This lesson will introduce some of the most fundamental and frequently used number- and text-based data classes available. However, before this discussion can occur, it is important to first understand how commands (i.e., code) are issued in Python.
2.2. The terminal#
At its most fundamental level, commands issued in Python are interpreted and executed via the Python shell. In a basic sense, the shell can be thought of as an application that executes code (in this case Python code). Many of the examples that we will cover in this guide consists of manually typing in commands to the shell. When a shell reads commands directly from our typed input, we refer to the shell as an interactive shell.
Definition: shell
The application that interprets and executes code (in this case Python code). An interactive shell reads commands provided by a user input (e.g., typing in commands).
The actual physical interface that a user interacts with the interactive shell is called the console (e.g., a computer). The programmer will often input commands and receive outputs from the console via a text-based interface, which is called the terminal. For simplicity, this guide will use console / terminal interchangeably.
Definition: console
The physical interface that a programmer uses when interacting with the shell.
Definition: terminal
A text-based input / output environment.
Hey! Listen!
Do not worry too much about semantics here between the console and terminal. In most modern day conversations, the words console and terminal are used interchangeably. This guide will primarily use the phrase terminal for consistency.
More often than not, the Python terminal will look like a simple text field to input code. However, since Python is an interpreted language, the terminal may look differently depending on what type of coding environment you are using (e.g., JupyterLab, PyCharm, Spyder, etc.). For example, JupyterLab, which we use in this guide, represents the terminal as empty blocks of code called “cells”. Regardless of the environment used, simple commands are issued to the Python interactive shell through the terminal.
But enough talk…let’s code! Open up a JupyterLab IPython notebook (see the earlier
Running JupyterLab notebooks section of the toolkit for details) and type the following code below
(i.e., 2 + 3
) into the first cell. Next, press both the SHIFT and ENTER keys simultaneously to have the interactive shell execute
the code. This is also known in JupyterLab as the “running the code” command.
2 + 3
5
Congrats on running your first Python code! As you see in your terminal (as well as the block of code above), the interactive shell
returned the value 5
. We have just used the Python interactive shell as a calculator. As you can guess, however, we can do so much
more…
Hey! Listen!
Did you notice that the numbers 2
and 3
were colored green and the +
symbol was colored grey in the block of code above?
JupyterLab is automatically marking various aspects of the code via color. This helps in readability of code. You will see
many other colors soon!
2.3. Variables#
One of the most useful things in coding is to assign a symbolic name to an object. This symbolic name is called a variable. Identifying a particular object with a name makes it easier for a programmer to identify and then modify a set of data. Variable assignment is common in all types of languages. Unlike many other programming languages, Python does not require one to declare a variable (i.e., create the name) prior to assigning it a value (i.e., associating data with it). In Python, you can declare and assign all at once.
Definition: variable
A symbolic name assigned to an object.
Hey! Listen!
Going forward, this toolkit will show numerous blocks of code for educational purposes. It is highly recommended that you retype out these blocks of code and run them in your own instance of JupyterLab (or your preferred Python environment). Like rewriting notes from a lecture or book, retyping and running the code will help you remember the information presented here!
Let us try to create a variable. The following code block below creates a variable called a
and assigns it the value of 2
.
a = 2
We can recall a
’s value by entering the following command into the terminal:
a
2
Now let us create a new variable called b
and assign it the value of 3
:
b = 3
Since a
and b
are assigned values 2
and 3
, respectively, let us see what the following command produces:
a + b
5
You get 5
! Therefore we can do symbolic operations with variables!
Note
Notice that in the code block above, spaces were placed between a
and +
and again between +
and b
. This is
optional, but it is often considered good practice for readability.
We can also reassign a variable. Let us reassign b
to now 10
, and reissue the addition operation in the following
block of code:
b = 10
a + b
12
Two things just happened in this block of code. The first and more obvious observation is that since we reassigned the
value of b
to 10
, the addition of the two variables results in the output of 12
. Second, notice that we issued two
lines of code in one cell. In JupyterLab this is done by pressing the ENTER key after the first line. Therefore, the Python
terminal can be issued multiple lines of code if needed.
Attention
Each coding environment handles multi-line code differently. JupyterLab handles this by pressing the ENTER key between each line. Pressing the SHIFT and ENTER keys simultaneously in JupyterLab tells the Python interactive shell to execute the code. These keyboard commands are not the same across coding environments. For example, the coding environment Spyder handles multi-line coding in the terminal by pressing the CRTL and ENTER keys simultaneously, and executes code in the terminal by pressing the ENTER key!
You can even assign a variable based on another variable’s value! See the following block of code below:
c = a
c + b
12
Here we have declared a new variable called c
and have assigned it the value of a
. Therefore when we issue the
command c + b
, we get the result of 12
.
But is c
actually its own unique variable or just a mapping to a
? While this may seem like a philosophical question,
it does have practical implications. To answer this question, we are going to issue our first Python function to help
us out. A function is a labelled code block that executes the code block when its name is called. Python has built-in functions
ready
for use, can import external functions from other code libraries, and allows for users to create their own functions!
Functions are very powerful, and we have an
entire lesson coming up that goes over the basics of functions. For now, just following along with
the exercise.
Definition: function
A labelled code block that executes when its name is called.
The function we are going to use is the id()
function, which
reads out the memory location of an object. The id()
function’s input is the object to be analyzed, and the output
is its memory location. To see how this works, the block of code below issues the id()
function on a
and c
.
For now, do not worry about the use of the ,
in the block of code below. This will allows for the time being to see
two outputs in the terminal.
id(a), id(c)
(140540682256656, 140540682256656)
Notice that the terminal outputs two integers. The first integer represents the memory address for a
and the second
integer represents the memory address for c
(note: running these commands on your own computer will probably result
in different memory locations). We can see that both variables are currently pointing to the same memory address. Here,
variable c
is being assigned to variable’s a
memory address. Therefore, they are exactly the same variable at this
point.
But what happens if you then change the data assigned to a
? Let us find out with the block of code below:
following code:
a = 5
id(a), id(c)
(140540682256752, 140540682256656)
Here we first reassign a
to the value of 5
and then ask again for the memory locations to a
and c
. Notice now
that a
has been assigned to a new memory location, while c
is still assigned to the older memory address. At this
point, a
and c
appear to be no longer the same value based on their memory locations.
What about their actual values? Run the following code and find out!
a, c
(5, 2)
Sure enough, the variable values are also now different! Therefore, the initial declaration and assignment of c
was only to a
’s initial memory location, but not to the value itself. More often than not, you will interact
with data using variable names rather than directly calling them by their value. Therefore, it is important to
become comfortable in declaring and assigning variables to objects.
2.3.1. Variable naming tips#
Tip 1: A variable name is not limited to a simple letter. You can write out an entire word if needed. See the example code below:
alpha = 200
beta = 50
alpha + beta
250
Code readability is important. Using entire words or shorthand versions of words can be useful in understanding variables.
Tip 2: While not required, it is HIGHLY recommended to follow the standard Python practice of NOT capitalizing the first letter of a variable’s name.
DO: “resistivity”
DO NOT: “Resistivity”
Tip 3: If you want multiple words in a variable name, there are two commonly used formatting options. One
option is to use the underscore character ( _
) between words. Another option is to use
camelCase typing in which the first letter in a new word gets capitalized
(remember to keep the first letter in the first word lowercase!). Avoid placing spaces in a variable name as that
will often cause a coding error.
DO: “elastic_modulus” or “elasticModulus”
DO NOT: “elastic modulus”
Tip 4: Most letters, phrases, or words can be used as a variable’s name, but there are a few to avoid. These strings of characters are usually associated with certain aspects of Python (e.g., int, def, float, etc.). One way to quickly identify an incorrect letter, phrase, or word is to notice if it changes color when typing them out in your coding environment (e.g., JupyterLab, Spyder). Normally, variable names will be listed in a black font color (assuming a white background). Therefore, if the proposed variable name changes color while you are typing, chances are that the letter, phrase, or word has a special significance in Python and should be avoided as a variable name.
2.3.2. Example: A simple beginning#
Recall that Newton’s second law of motion relates the force that is acted on an object to the object’s mass and acceleration via the relationship,
where \(F\) is the force , \(m\) is the object’s mass, and \(a\) is the object’s acceleration. Calculate the amount of force needed (unit: newton, N) for a 10 kg object that is accelerated to 13 m/s2.
Note: to multiply two numbers together, use the *
symbol. We will go over mathematical operations in an
upcoming lesson!
Solution:
This is a fairly straightforward analysis. We first need to define variables for the mass and acceleration (let’s use
mass
and acceleration
, respectively) and then we multiply the two variables together using the *
operator. See
the block of code below for details:
mass = 10
acceleration = 13.2
mass * acceleration
132.0
2.4. The print()
function#
You may have noticed that our terminal appears to output just a single line of text so far. This has
made reading the interactive shell’s output somewhat cumbersome at times, and if we wanted to get multiple pieces of output we had
to do some tricks (see our earlier discussion about variable names). One easy way to get multiple
lines of output is to use the very popular built-in function
print()
. In essence, this function “prints” an argument
to the terminal. While there are some details we are glossing over here, new users simply need to know that
we can use the print()
function to print things out to the terminal, which will allow us for multi-lined outputs! Let
us see this in action using the following code:
a = 5
b = 7
print(a)
print(b)
5
7
Here, we have re-assigned the values for a
and b
here just for completeness. Notice the command print(a)
in the
third line, which is interpreted as “print out the value of a
”. The fourth line is the command print(b)
. The
output for this code block are two values listed in chronological order: the value of a
followed by the value of b
.
The print()
function can also accept complex commands and other functions as inputs! The ability to pass functions
through functions is a really useful feature in Python. The block of code below demonstrates this:
print(a + b)
print(id(a))
12
140540682256752
The first print()
command displays the addition of a + b
to the terminal and the second print()
command displays
the memory location of a
using the id()
function from earlier. The print()
function is very useful
when coding in Python, and we will use it frequently going forward. We will revisit the print()
in an
upcoming lesson to see other ways we can utilize this useful function.
2.4.1. Example: Displaying to the world#
Redo the previous example about Newton’s second law of motion, but now display the mass,
acceleration, and force to the terminal using the print()
function.
Solution:
This example builds off the previous example by defining a force variable (force
) and then
using three print()
calls.
mass = 10
acceleration = 13.2
force = mass * acceleration
print(mass)
print(acceleration)
print(force)
10
13.2
132.0
As seen here, the print()
function is extremely useful as it allows us to display multiple values to the terminal.
2.5. Basic number types: integer
, float
, and complex
#
Python has three built-in classes for numbers: integers (class code: int
), floating point numbers (class code:
float
), and complex numbers (class code: float
). Each number type has a unique role in Python, so it is
important to be familiar all three types.
2.5.1. Integers (int
)#
Integers (class code: int
) are real positive and negative whole numbers. The numbers previously used in our
codes so far have all been integers. To verify this, we can use the built-in function
type()
to return an object’s class. The block of code
below uses type()
on three integers:
alpha = 310
a = 2342523
count = -53
print(type(alpha))
print(type(a))
print(type(count))
<class 'int'>
<class 'int'>
<class 'int'>
In all three cases, each variable is associated with the int
class, meaning they all are integers.
Note
Notice the extra line return between variable assignment and the print()
commands in the block of code above.
This is simply done for readability purposes and is not required for the code to execute.
2.5.2. Floating point numbers (float
)#
Floating point numbers (class code: float
) are real numbers that have decimal points. As engineers and scientists,
this will probably be the most common number class you will use. Creating float
objects is similar to int
objects;
the only difference is that we need to make sure there is a decimal point somewhere in number. The block of code below
creates three different floating point numbers:
gamma = 25.3
y = -1.35e5
wavelength = 0.15459
print(type(gamma))
print(type(y))
print(type(wavelength))
<class 'float'>
<class 'float'>
<class 'float'>
The return for type()
on all three variables is <class 'float'>
, meaning each variable is a float
.
Hey! Listen!
Notice that we assigned the variable y
the number -1.35e5
. Python can accept scientific notation using the e
character, which represents base 10. So the value of y
is \(-1.35\cdot 10^5\).
2.5.3. Complex numbers (complex
)#
Python even has a built-in class for complex numbers (class code: complex
). Python represents \(\sqrt{-1}\) with the
characters j
and J
(in this guide we will use j
). One way to create a complex number is to write it out directly
when assigning a variable. Below are a few examples of using this route:
w = 3+5j
x = -1.5 +7j
y = -1.35j
z = 19 + 0j
print(type(w))
print(type(x))
print(type(y))
print(type(z))
<class 'complex'>
<class 'complex'>
<class 'complex'>
<class 'complex'>
Another way to create complex numbers is to use the
complex()
function. It has two inputs: real
and imag
that represent the real and imaginary parts of a complex number, respectively. The function is written as
complex(real, imag)
. By default, each value is assigned 0
, so if we ignore a particular input, Python will
assign that input the value 0
. Examples of creating complex numbers are shown below:
phi = complex(real = 5, imag = 7.2)
chi = complex(23, 8)
theta = complex(imag = 2)
print(phi)
print(chi)
print(theta)
(5+7.2j)
(23+8j)
2j
Note
There are numerous ways to enter inputs to a function. We will revisit these various ways in a later lesson on functions.
2.5.4. Example: A dense calculation#
The density of a material is defined as,
where \(\rho\) is the density, \(m\) is the mass of an object made from the material being studied, and \(V\) is the volume of the object. Calculate the mass of an aluminum bar that has a density of 2.7 g/cm3 and a volume of 4.5 cm3. Have the Python terminal report both the mass and the data type that the mass variable represents.
Solution:
First, we need to rearrange the above equation in terms of the mass,
Then, we create the variables density
and volume
. Multiplying these two variables together gives us the mass
(with variable name mass
). Finally, we print out the mass to terminal using the print()
function and use the
type()
function to get its data type. The block of code below shows how this can be done:
density = 2.7
volume = 4.5
mass = density * volume
print(mass)
print(type(mass))
12.15
<class 'float'>
2.6. Text type: strings (str
)#
In addition to numbers, Python can also parse “strings” of text (class code: str
). This text can be of any unicode
character such as a letter, simple symbol, or number. Strings are extremely important when coding in scientific
applications. For example, strings are often used as output to the terminal or to a file. Furthermore, data sent to and
from instruments is often in the form of a string of characters. Therefore, it is important to know the basics of
creating and manipulating strings.
Declaring and assigning a string is straightforward: one simply writes out the text to be included in the string between
double quotes ("
"
). Try the code block below that creates the str
variable a
, and then confirms its type:
a = "The quick brown fox jumps over the lazy dog"
print(type(a))
<class 'str'>
Note the str
class output, which is how Python designates a string.
Note
The above example uses double quotes to designate a string. Python also allows single quotes (‘
’
) and even triple
quotes (‘‘‘
‘’’
or “““
”””
). There are minor advantages to using any one of these three options. However, for
the purpose of this guide, we will stick to using the double quotes format (“
”
).
As you can probably guess, the print()
function also works with strings. You can pass a str
-based object into
print()
as a variable or by directly typing it out. The block of code below shows a few examples on displaying
str
objects with print()
.
a = "The quick brown fox jumps over the lazy dog"
print(a)
print("Hello World!")
print("Chemical Engineering & Materials Science")
print("The resistivity of the sample is 1.525 uOhm*cm.")
The quick brown fox jumps over the lazy dog
Hello World!
Chemical Engineering & Materials Science
The resistivity of the sample is 1.525 uOhm*cm.
Strings are extremely important in coding and can be manipulated in many ways. As such, a later lesson in this guide further explores the uses of strings.
2.6.1. Example: What’s your name?#
Create a variable called name
that contains your full name. Print out your name to the terminal and also
confirm that name
is part of the str
class.
Solution:
Overall, a quick example for us as we simply need to create name
and use both the print()
and type()
functions
to display our name and confirm that name
is indeed a str
object. See the block of code below for details.
name = "Goldy Gopher"
print(name)
print(type(name))
Goldy Gopher
<class 'str'>
2.7. Casting#
What if we want to declare an object into a specific class or convert an object from one class to another? This process is called casting. Since we now know a few different class types, let us see how we can convert data between class types.
Definition: casting
The process of changing an object’s data class to another.
For example, the int()
function converts a float
to an
int
. The following examples below show how this can be done:
a = int(5.1)
b = int(5.999999999)
c = int(-27656.6)
d = 0.154
e = int(d)
print(a)
print(b)
print(c)
print(e)
print(type(d))
print(type(e))
5
5
-27656
0
<class 'float'>
<class 'int'>
Notice that in all cases, int()
rounds each float
down to the nearest ones position. Another way to think about how
this works is that it simply cuts out all values past the decimal point.
The float()
function converts an int
object to a float
object. To see this, observe the following block of code:
a = 245
b = float(a)
print(a)
print(type(a))
print(b)
print(type(b))
245
<class 'int'>
245.0
<class 'float'>
Here, b
is a float
that is built from a
, which is an int
. The conversion of an int
to a float
will append
a .0
value to the end of the number.
While casting numbers between int
and float
is straightforward, you cannot cast a complex
object into the int
or float
classes. Python will return an error similar to what is shown below in which a complex
object is trying
to be cast as an int
(look at the final output line that starts with TypeError
):
position = 12.5 + 23j
print(int(position))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [26], in <cell line: 2>()
1 position = 12.5 + 23j
----> 2 print(int(position))
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'complex'
Here is a similar example in trying to cast a complex
object as a float
:
position = 12.5 + 23j
print(float(position))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [27], in <cell line: 2>()
1 position = 12.5 + 23j
----> 2 print(float(position))
TypeError: float() argument must be a string or a real number, not 'complex'
Another common casting scenario is to cast an int
, float
, or complex
object as a str
object. This is done using
the str()
function. The example below casts a float
object as a str
:
a = 2.56
b = str(a)
print(type(a))
print(type(b))
<class 'float'>
<class 'str'>
2.7.1. Example: Casting numbers#
First, create a str
object that contains the text 3.14
and then cast it as both an float
and int
. Do you run
into an error if you cast your str
object directly as an int
? What could you do to correct this issue?
Solution:
Casting a number that starts as a string to a floating point number or an integer is a very common process in
science and engineering applications. This often occurs when reading data from an instrument, as data is often sent
as a string. Let’s first try to convert our number (called str_number
) to float
and int
objects using the
float()
and int()
functions, respectively.
str_number = "3.14"
float_number = float(str_number)
int_number = int(str_number)
print(str_number)
print(float_number)
print(int_number)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [29], in <cell line: 4>()
1 str_number = "3.14"
3 float_number = float(str_number)
----> 4 int_number = int(str_number)
6 print(str_number)
7 print(float_number)
ValueError: invalid literal for int() with base 10: '3.14'
Hmm…it appears that Python does not want to directly convert a str
object directly into an int
. We do know
casting a float
to an int
is allowed, so let’s use our float_number
in the int()
call.
str_number = "3.14"
float_number = float(str_number)
int_number = int(float_number)
print(str_number)
print(float_number)
print(int_number)
3.14
3.14
3
Now we get no errors and the expected behavior!
2.8. Concluding thoughts#
In this lesson, you started your journey on learning the Python programming language. First, you learned how to interface with the Python console, and then you began to explore some important, built-in numbers and text object classes. In our next lesson, we will continue to explore a few more data classes that you will commonly use in Python including logic-based, sequence-based, and mapping-based data classes.
2.9. Want to learn more?#
Python Software Foundation - Standard Library Types
Python Software Foundation - Built-in Functions
W3Schools - Python Tutorial