# 1.3. Coding Basics#

Before we jump into the textbook, we should cover a few basic aspects of programming that the reader may not know. These are some of the most essential terms and concepts that you will see used throughout this textbook. Remember, you can always come back to this section if you forget one of these terms.

## 1.3.1. The Print Function#

The very first thing that every programmer learns is how to print something off using that programming language. In most tutorials, you will see the phrase “Hello, World!” used. In this textbook, let’s try something a bit different. Let’s say I wanted to print off “Hello, William”. We can do this in Python by using the print function. The print function lets us print off some piece of data. In our case, that piece of data will be a piece of text, known as a string (see below). Our text is “Hello, William”. The thing that we want to print off must be located between an open parentheses and a close parentheses. Let’s try to execute the print command in the cell below.

print("Hello, William!")

Hello, William!


As we can see, the code that we typed in the Jupyter cell outputted beneath it. Now, it is your turn. Try to print off something. In order to print off text, you will need to use an open and a close quotation mark. We will learn more about this as we meet strings in the next chapter.

from IPython.display import IFrame
IFrame('https://trinket.io/embed/python3/3fe4c8f3f4', 700, 500)


This has worked wonderfully, but what if our Python notebook needs to be more dynamic, meaning it needs to adjust based on some user input. Perhaps, we need to use a name other than William based on some user-defined input. To do this, we would need to store a piece of data in memory. We can do this in Python by creating a variable that will point to an object. Before we get into how this is done, let’s first get to know objects and variables.

## 1.3.2. Objects#

When we import or create data within Python, we are essentially creating an object in memory with a variable. These two words, object and variable mean slightly different things, but are often used interchangeably. We will not get into the complexities of their differences and why they exist in this textbook, but for now, view an object as something that is created by a Python script and stored in your computer’s memory so that it can be used later in a program.

Think of your computer’s memory rather like your own brain. Imagine if you needed to remember what the word for “hello” in German. You may use your memory rather like a flashcard, where “hello” in English equates to “hallo” in German. In Python, we create objects in a similar way. The object would be the dictionary entry of “hello: hallo”.

## 1.3.3. Variables#

In order to reference this dictionary entry in memory, we need a way to reference it. We do this with a variable. The variable is simply the name of the item in our script that will point to that object in memory. Variables make it so that we can have an easy-to-remember name to reference, call, and change that object in memory.

Variables can be created by typing a unique word, followed by an = sign, followed by the specific data. As we will learn throughout this chapter, there are many types of data that are created differently. Let’s create our first object before we begin. This will be a string, or a piece of text. (We will learn about these in more detail below.) In my case, I want to create the object author. I want author to be associated with my name in memory. In the cell, or block of code, below, let’s do this.

author = "William Mattingly"


Excellent! We have created our first object. Now, it is time to use that object. Below, we will learn about ways we can manipulate strings, but for now, let’s simply see if that object exists in memory. We can do this with the print function.

The print function will become your best friend in Python. It is, perhaps, the function I use most commonly. The reason for this is because the print function allows for you to easily debug, or identify problems and fix them, within your code. It allows us to print off objects that are stored in memory.

To use the print function, we type the word print followed by an open parentheses. After the open parentheses, we place the object or that or piece of data that we want to print. After that, we close the function with the close parentheses. Let’s try to print off our new object author to make sure it is in memory.

print(author)

William Mattingly


Notice that when I execute the cell above, I see an output that relates to the object we created above. What would happen if I tried to print off that object, but I used a capital letter, rather than a lowercase one at the beginning, so Author, rather than author?

## 1.3.4. Case Sensitivity#

print(Author)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [3], in <cell line: 1>()
----> 1 print (Author)

NameError: name 'Author' is not defined


The scary looking block of text above indicates that we have produced an error in Python. This mistake teaches us two things. First, python is case sensitive. This means that if any object (or string) will need to be matched in not only letters, but also the case of those letters. Second, this mistake teaches us that we can only call objects that have been created and stored in memory.

Now that we have the variable pointing to a specific piece of data, we can make our print function above a bit more dynamic. Let’s try and print off the same statement as before, but with the new full author name. I don’t expect you to understand the specifics of the code below, rather simply understand that we will frequently need to store variables in memory so that we can use them later in our programs.

print(f"Hello, {author}!")

Hello, William Mattingly!


## 1.3.5. Reserved Words#

When working with Python, there are a number of words known as reserve words. These are words that cannot be used as variable names. As of Python version 3.6, there are a total of 33 reserve words. In can sometimes be difficult to remember all of these reserve words, so Python has a nice built in function, “help”. If we execute the following command, we will see an entire list.

help("keywords")

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               class               from                or
None                continue            global              pass
True                def                 if                  raise
and                 del                 import              return
as                  elif                in                  try
assert              else                is                  while
async               except              lambda              with
await               finally             nonlocal            yield
break               for                 not


These are words that you cannot use as a variable name.

## 1.3.6. Built-in Types#

In addition to reserve words, there are also built-in types in Python. These are words that you can use (as we will see) to convert one type of data into another. There are 94 of these in total. Unlike reserve words, you can use a built-in type as a variable name. It is, however, strongly discouraged to do so because it will overwrite the intended use of these variable names in your script.

import builtins
[getattr(builtins, d) for d in dir(builtins) if isinstance(getattr(builtins, d), type)]

[ArithmeticError,
AssertionError,
AttributeError,
BaseException,
BlockingIOError,
BrokenPipeError,
BufferError,
BytesWarning,
ChildProcessError,
ConnectionAbortedError,
ConnectionError,
ConnectionRefusedError,
ConnectionResetError,
DeprecationWarning,
EOFError,
OSError,
Exception,
FileExistsError,
FileNotFoundError,
FloatingPointError,
FutureWarning,
GeneratorExit,
OSError,
ImportError,
ImportWarning,
IndentationError,
IndexError,
InterruptedError,
KeyError,
KeyboardInterrupt,
LookupError,
MemoryError,
ModuleNotFoundError,
NameError,
NotImplementedError,
OSError,
OverflowError,
PendingDeprecationWarning,
PermissionError,
ProcessLookupError,
RecursionError,
ReferenceError,
ResourceWarning,
RuntimeError,
RuntimeWarning,
StopAsyncIteration,
StopIteration,
SyntaxError,
SyntaxWarning,
SystemError,
SystemExit,
TabError,
TimeoutError,
TypeError,
UnboundLocalError,
UnicodeDecodeError,
UnicodeEncodeError,
UnicodeError,
UnicodeTranslateError,
UnicodeWarning,
UserWarning,
ValueError,
Warning,
OSError,
ZeroDivisionError,
_frozen_importlib.BuiltinImporter,
bool,
bytearray,
bytes,
classmethod,
complex,
dict,
enumerate,
filter,
float,
frozenset,
int,
list,
map,
memoryview,
object,
property,
range,
reversed,
set,
slice,
staticmethod,
str,
super,
tuple,
type,
zip]


Of this long list, I recommend paying particular attention to the ones that you are more likely to write naturally: bool, dict, float, int, list, map, object, property, range, reversed, set, slice, str, super, tuple, type, and zip. You are more likely to use these as variable names by accident than, say, ZeroDivisionError; and this shorter list is a lot easier to memorize.

## 1.3.7. Type Function#

It is frequently necessary to check to see what type of data a variable is. To identify this, you can use the built-in function type in Python. To use type, we use the command below with the data we want to analyze placed between the two parentheses.

type("this is a string...")

str


## 1.3.8. Bugs#

Throughout your programming career, you will often read or hear about bugs. A bug is a problem in your code that either returns an error or an unintended result in the output. Tracing down bugs and fixing them is known as debugging. Aside from figuring out how to code solutions to problems, debugging can be one of the more time-consuming aspects of writing a program, especially if it is quite complex. Throughout this textbook, we will encounter common errors so that you can see them in this controlled space. We will also walk through what the error means and how to resolve it. That said, you are likely to create many other bugs as you try to apply the code in this textbook to your own data. That is expected. Always remember to read each line of your Pyhon carefully and, if you have an error message, identify where the error is coming from and what it is.