An Informal Introduction to Python

Now that you have the Anaconda distribution of Python installed on your machine, let’s write some simple Python code! We are going to forego writing a full Python script for now, and instead make use of a convenient tool for doing quick code scratchwork. The IPython console was installed as a part of Anaconda; it will allow us to build incrementally off of snippets of code, instead of having to execute an entire script all at once.

Let’s open an IPython console. Open your terminal if you are a Mac/Linux user, or start cmd.exe if you are a Windows user. Now type ipython into the console and hit <Enter>. You should see the following display on your screen:

IPython console example

We can type small pieces of Python code into this console, and then simply hit <Enter> to have the CPython interpreter execute our code immediately within the IPython console!

Let’s acquaint ourselves with Python’s numbers, strings, and lists. In doing so, we will learn about the Python standard library, and how to make use of its modules, like the math module. IPython’s autocompletion and documentation-display utilities will provide a nice means for exploring the library and the functionality built into the different types of Python objects. A quick glimpse at Python’s strings and lists will hint at the common interface Python provides for working with sequences of objects, while highlighting some of the nice features of these all-important data types.

Dabbling with Numbers

Time to execute some Python code that performs simple arithmetic. Typing 2 + 3 into the IPython console and hitting the <ENTER> key, you should see the following input and output in the console:

[1]:
2 + 3
[1]:
5

This console session is persistent, meaning that we can define a variable and then reference it in our code later on within this console session. Let’s define the variable x and assign it to the integer 10 (please follow along in the IPython console)

[2]:
x = 10

We can check the contents of x in this console by simply entering x in the next line and hitting <ENTER>:

[3]:
x
[3]:
10

Now, let’s use x in a quadratic equation \(x^{2} + 2x + 3\), and compute this total.

[4]:
x**2 + 2*x + 3
[4]:
123

Python’s “standard library”, the various tools and functions that come packaged as part of the core language, includes plenty of familiar mathematical functions. As a matter of organization, Python stores these mathematical functions away in a module named “math”. To make use of this math module, we must import it into our code.

[5]:
import math

Having imported it, the term math now refers to the math module in our code. IPython provides a nice way for us to see a list of all the functions that are provided by the math module. To utilize this, type into the console math. (note the trailing period) and then hit <TAB>. You should see this list appear:

Displaying the contents of the math module

In general, hitting <TAB> will cue IPython to try to autocomplete code for you. This menu displays all the valid things that you could type after math.. Looking at the functions starting with “s”, we see sqrt(). This is the square root function. To see autocompletion in action, type math.sq and then hit <TAB>. You should see the code autocomplete to math.sqrt.

Let’s use this function to compute \(\sqrt{100}\):

[6]:
math.sqrt(100)
[6]:
10.0

You might wonder why the result displayed as 10.0 and not simply as 10; in Module 2 we will see that these are two different types of numbers in the Python language. The former is called a floating-point number, indicating the presence of its decimal point, whereas the latter is an integer. The math.sqrt function is defined such that it always returns its results as floating-point numbers.

In the case that we want to make frequent use of a certain function from the math module, it’d be nice to avoid having to type out the math module prefix, math., repeatedly. We can accomplish this by importing an individual function from the math module. Let’s import the factorial function from the math module.

[7]:
from math import factorial

We can now make use of the factorial function in our code. Recall that 5-factorial is \(5! = 5\times 4\times 3\times 2\times 1 = 120\)

[8]:
factorial(5)
[8]:
120

Messing with Strings

In the context of code, written text is referred to as a string of characters, or string for short. Python is an excellent language for doing text-processing work as it provides many convenient, efficient functions for working with strings.

To begin, we simply form a string by typing characters between quotation marks:

[9]:
"the cat in the hat"
[9]:
'the cat in the hat'

Single quotes also work:

[10]:
'the dog in the sash'
[10]:
'the dog in the sash'

If you use single quotes to form a string, then that string is able to contain the double-quote as a character (and vice versa):

[11]:
'He picked up the phone, "Hello? What do you want?" Bob was a rather impolite dude.'
[11]:
'He picked up the phone, "Hello? What do you want?" Bob was a rather impolite dude.'

There are designated special characters that allow us to affect the way a string is formatted when it is printed to the string. For example, if \n ever occurs in a string, it is treated as a single character that indicates a line-break. This will only manifest if such a string is fed to the built-in print function, which informs the computer to print text to a user’s screen.

Let’s create a string that will display as three separate lines, when printed to the screen.

[12]:
print("I like to talk to dogs.\nI like to talk to cats.\nWhat's my deal?")
I like to talk to dogs.
I like to talk to cats.
What's my deal?

Of course, strings are useful beyond merely containing text! Let’s explore some ways to manipulate strings. First, we’ll write a string and assign it to a variable named sentence:

[13]:
sentence = "Who would have thought that we were robots all along?"

Let’s see how many characters are in this string by checking the “length” of this sequence of characters:

[14]:
len(sentence)
[14]:
53

We can access the first 4 characters in the string, the last 6 characters, or a few characters in the middle by “slicing” the string:

[15]:
sentence[:4]
[15]:
'Who '
[16]:
sentence[-6:]
[16]:
'along?'
[17]:
sentence[5:22]
[17]:
'ould have thought'

We can also check to see if some other string is contained within our string. Is the string "robot" contained within sentence?

[18]:
"robot" in sentence
[18]:
True

As a quick way to check out the built-in functions that strings have available to them, we can make use of IPython’s autocompletion feature once again. Type sentence. (including the trailing period) and then hit <TAB>. A menu of functions should appear as so:

Built-in functions for a string

Let’s use the count function to tally the number of lowercase w’s in sentence

[19]:
sentence.count('w')
[19]:
3

Let’s see what the replace function does. IPython provides a great utility for looking up the documentation for a function by simply putting two question marks after the function name. For example:

Looking up documentation for a function

Putting our newfound understanding of the string’s replace function, let’s replace “robot” with “computer”:

[20]:
sentence.replace("robot", "computer")
[20]:
'Who would have thought that we were computers all along?'

Playing with Lists

A list is one of several types of containers that are built into Python’s standard library. It can hold a sequence of Python objects. We can create a list of numbers:

[21]:
[-1, 1/3, 10*2, 7-1]
[21]:
[-1, 0.3333333333333333, 20, 6]

A list can contain any type of Python object; it can store a mix of numbers, strings, other lists, and much more!

[22]:
[1, 2, "a", 0.5, "apple and orange"]
[22]:
[1, 2, 'a', 0.5, 'apple and orange']

You can join lists together, which is known as concatenation.

[23]:
[1, 2, 3] + ["a", "b", "c"]
[23]:
[1, 2, 3, 'a', 'b', 'c']

Like a string, a list is sequential in nature and we can access the items in a list by specifying its position in the sequence. This is known as “indexing” the list; the index of the first item in a sequence is always 0.

[24]:
my_list = [10, 20, 30, 40, 50, 60]
[25]:
my_list[0]
[25]:
10
[26]:
my_list[1]
[26]:
20

Negative integers can be used to index relative to the end (right-side) of the list.

[27]:
my_list[-1]
[27]:
60

You can change an entry in a list by assigning it to a new value.

[28]:
-5 in my_list
[28]:
False
[29]:
my_list[1] = -5
[30]:
my_list
[30]:
[10, -5, 30, 40, 50, 60]
[31]:
-5 in my_list
[31]:
True

We can also access multiple items in a list at once by slicing the list, like we did with the string.

[32]:
my_list[:3]
[32]:
[10, -5, 30]

This slice can be used to update the first three entries of the list

[33]:
my_list[:3] = "abc"
[34]:
my_list
[34]:
['a', 'b', 'c', 40, 50, 60]

To wrap up this quick demo, let’s append an new entry to the end of this list.

[35]:
my_list.append("moo")
[36]:
my_list
[36]:
['a', 'b', 'c', 40, 50, 60, 'moo']