Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

2 The Very Basics: Numbers and Text

2.1Lesson goals

2.2Overview

The start of any journey can feel overwhelming and aimless at times. This is especially true when learning a new programming language (or even your first programming language). Understanding the basics ways to create and modify data is key to being successful in the long term. This lesson is designed to lay the important foundational underpinnings to programming with Python. While you won’t be expert in Python programming at the end of this lesson, you will have a solid starting point to understanding the more advanced topics that will be introduced throughout this guide.

2.3Objects and classes

The creation, modification, and deletion of data lies at the heart of programming. 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!

Python groups similar objects together in a unit called a class. There are many classes in Python, and you can even create your own classes. Each class will have its own unique functionality, requirements, and limitations.

It is therefore important to understand some of the basic, built-in data classes that are available in Python. This lesson will introduce a few fundamental and commonly used number-based 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.4The Python interpreter and shell

At its most fundamental level, commands issued in Python are interpreted and executed via the Python interpreter. The interpreter is a program that reads code, interprets its meaning, and then executes the commands. Therefore, Python is called an “interpreted language”. This is different than a compiled-based language like C, C++, assembly, and Rust in which code is translated into its own executable program. Both forms of languages have their advantages and disadvantages. For this guide, you just need to know that Python is an interpreted language that requires a Python interpreter to run code.

The interface that allows us to communicate with the interpreter is known as the shell. 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 and provides a response, we refer to it as an interactive shell.

More often than not, the shell interface will look like a simple text field to input code. Since Python is an interpreted language, the shell may look differently depending on what type of coding environment you are using (e.g., JupyterLab, VS Code). For example, an interactive Python notebook file (i.e., an IPython notebook file) represents the shell as empty blocks of code called “cells”.

But enough talk…let’s code! Open up an 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 keyboard keys simultaneously keys simultaneously to have the interactive shell execute (a.k.a., “run”) the code.

# Press the SHIFT and ENTER keyboard keys simultaneously to execute the code.
# The # symbol represents a comment!

2 + 3
5

Congrats on running your first Python code! We have just used the interactive shell as a calculator. As you can guess, however, we can do so much more.

The code block above only has one meaningful command for the Python interpreter to process, which is the 2 + 3 command. The other two lines are ignored by the interpreter because they have the hash character (#) at the start of the line. The text after each # character are called comments and are there for a human to better understand the code.

There are numerous ways you can utilize comments in your code. Below is an example of a few different ways we can express comments:

# This is an example of a whole line comment!

2 + 3 # This is an example of an in-line comment!

# The 2 + 3 part will get processed.

# Use in-line comments sparingly -> can be difficult to read at times

# 4 + 6 <- this command gets ignored, useful for debugging purposes

# Here is an example
# of a multi-lined / block
# comment!
# Notice that you need to use a # for each line.
# There is no dedicated multi-line command in Python.
5

Commenting is extremely important and you should always add it to your code for documentation purposes. You may come back to your code days, weeks, months, or years later, and comments help remind you of what the code does. The Python style guide also has additional recommendations on code comments. In short, make sure to comment your code!

2.6Variables

A variable is a symbolic name that is assigned to an object. Identifying a particular object with a name makes it easier for a programmer to identify data. Assigning variable names to objects is common in all types of languages, and this is no different in Python.

Let’s create a variable. The code block below creates a variable called a and assigns it the value of 2.

a = 2

We can recall a’s value by typing the following command into the shell:

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’s see what the following command produces:

a + b
5

You get 5! Therefore we can do symbolic operations with variables!

We can even reassign the value of a variable:

a = 10
a + b
13

Our output is now 13 since we reassigned a. Also notice that we issued two lines of code in one cell. Many interactive IDEs that use code cells allow for this (e.g., JupyterLab, VS Code). Therefore, we can issue multiple commands to the Python interpreter at once.

You can even assign a variable based on another variable’s value:

c = a
c + b
13

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 13.

Is c actually its own unique variable or just a mapping to a? Let’s use our first Python function to find out. A function is a block of code that can be executed when its name is called. Python has many built-in functions available for use. We can also import functions from other code libraries and even create our own functions in Python.

id(a), id(c)
(11278216, 11278216)

Notice that the shell’s output has 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:

a = 5
id(a), id(c)
(11278056, 11278216)

Here we first reassign a to the value of 5 and then ask again for the memory locations of a and c. Notice now that a has been assigned to a new memory location, while c is still assigned to its original 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, 10)

Sure enough, the values tied to the variables are also now different! 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.6.1Variable naming tips

Below are a few useful tips when creating variable names.

2.6.1.1Tip 1: Use words as variable names

A variable name is not limited to a simple letter. You can write out an entire word if you want:

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.

2.6.1.2Tip 2: Avoid first letter capitalization

While not required, it is HIGHLY recommended to follow the standard Python practice of NOT capitalizing the first letter of a variable’s name.

2.6.1.3Tip 3: Multi-word name formatting

Multi-word variable names require either the underscore character ( _ ) or the camelCase typing style. Avoid placing spaces in a variable name as that will often cause a coding error:

2.6.1.4Tip 4: Some names are off limits

There are certain letters, phrases, or words that should be avoided when creating a variable name (e.g., int, def, float, etc.). Your coding environment will usually flag these with a different color.

Placing a single underscore at the start of a variable name (e.g., _hiddenVariable) implies that the object should be considered “hidden” (i.e., not readily accessed). Python does not actually forbid access to the object, it is simply of a convention that programmers use. There is nothing special about the variable simply because of the leading subscript, you can still readily access it if you know variable name. The example code block below demonstrates accessing this not so hidden variable:

_hiddenVariable = 2.3
_hiddenVariable
2.3

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,

F=maF=ma

where FF is the force , mm is the object’s mass, and aa is the object’s acceleration. Calculate the amount of force needed (unit: newton, N) for a 10 kg10 \text{ kg} object that is accelerated to 13 m/s213 \text{ m} / \text{s}^2.

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.7The print() function

You may have noticed that our outputs from the shell are currently just a single line of text. 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 important built-in function print(). In essence, this function “prints” an input argument from the shell. While there are some details we are glossing over here, for now you just need to know that we can use the print() function to display things out to the terminal, which will allow us for multi-lined outputs. Let’s 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 for completeness. The command print(a) in the third line tells the interpreter to “print out the value of a. A similar command is issued in the fourth line for b. The “printing” of these outputs occur in chronological order: the value of a followed by the value of b.

The print() function also accepts complex commands and other functions as inputs. The ability to pass functions through functions is a really useful feature in Python and is demonstrated below:

print(a + b)
print(id(a))
12
11278056

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.7.1Example: 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.8Basic number classes: int, 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.8.1Integers (int)

# Examples of int objects

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.

2.8.2Floating point numbers (float)

Floating point numbers (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:

# Examples of float objects

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.

2.8.3Complex numbers (complex)

Python represents complex numbers (complex) using either j or J for 1\sqrt{-1} (we will use j in this guide). 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'>

We can also use the built-in function complex(). It has two inputs: real and imag and 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 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

The density of a material is defined as,

ρ=m/V\rho = m / V

where ρ\rho is the density, mm is the mass of an object, and VV is the volume of the object. Calculate the mass of an aluminum bar that has a density of 2.7 g/cm32.7 \text{ g} / \text{cm}^3 and a volume of 4.5 cm34.5 \text{ cm}^3. Have the Python shell report both the value and the data type of the variable that represents the mass.


Solution:

First, we need to rearrange the above equation in terms of the mass,

m=ρVm = \rho V

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 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'>

Python can also parse strings of text (str). This text can contain any standard Unicode character such as a letter, simple symbol, or number. Strings are extremely important when coding in scientific and engineering applications. Strings are used to convey information from a program or data stored in a file. Furthermore, data sent to and from instrumentation 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 str object is straightforward: write out the text to be included between either single quotes ( ), double quotes (" "), or triple quotes (‘‘‘ ‘’’ or “““ ”””). The example below uses double quotes:

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. In a practical sense, the choice of quotes is up to you. There are minor advantages to using any one of these three options. For simplicity, we will often use either single quotes (' ') or double quotes ( ) as you will often see these formatting options in practice.

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 code block below shows a few examples of this:

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 programming and can be manipulated in many ways. As such, a later lesson in this guide further explores the uses of strings.

2.9.1Example: What’s your name?

Create a variable called name that contains your full name. Have the interactive shell print out your name 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'>

Casting is the process of changing an object’s data class to another class. This is a common occurrence when programming for scientific and engineering applications in which data maybe provided in a different class than what you need. For example, data sent to and received instrumentation is often handled using the str class, but you may need to process the data in the form of a float. So we need to be able to switch between classes effortlessly.

Python provides the built-in functions int(), float(), complex(), and str() to cast objects into int, float, complex, and str classes, respectively. Technically, these are initialization functions for each class, but you will often encounter using them when casting an object from one data type to another data type. The code block below demonstrates different casting examples:

# Example of float -> int casting
a = int(5.1)
print(a)
print(type(a))

# Example of int -> float casting
b = float(23)
print(b)
print(type(b))

# Example of float -> complex casting
c = complex(3.14)
print(c)
print(type(c))

# Example of complex -> str casting
d = str(3 + 5j)
print(d)
print(type(d))
5
<class 'int'>
23.0
<class 'float'>
(3.14+0j)
<class 'complex'>
(3+5j)
<class 'str'>

There are limits to what we can cast. Below is a failed attempt cast a complex object to a float object.

# Bad example of casting complex -> float

e = 6.7 - 8.3j
print(e)
print(type(e))

f = float(e)
print(f)
print(type(f))
(6.7-8.3j)
<class 'complex'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[27], line 7
      3 e = 6.7 - 8.3j
      4 print(e)
      5 print(type(e))
      6 
----> 7 f = float(e)
      8 print(f)
      9 print(type(f))

TypeError: float() argument must be a string or a real number, not 'complex'

We end up with a TypeError on Line 7. Python error handling is very useful and we will explore how Python handles errors in a later lesson. Keep in mind that casting is not always possible.

2.10.1Example: 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)
Cell In[28], line 4
      1 str_number = "3.14"
      2 
      3 float_number = float(str_number)
----> 4 int_number = int(str_number)
      5 
      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. Casting order matters!

2.11Final thoughts

In this lesson, you started your journey on learning the Python programming language. First, you learned how to interface with the Python interpreter using a shell prompt, and then you began to explore some important, built-in numbers and text classes. These simple beginnings lay a solid foundation for us as we begin to learn how to use Python for scientific and engineering applications. There is much more to learn, so let’s continue our journey!