Analyzing Data in Python

What is Python?

Before we do any analysis in Python, we need to understand what it is. Python is a programming language, which is a set of commands and rules that allows us to interact with and provide instructions to computers.

Arithmetic

We can use Python to perform common arithmetic operations:


In [1]:
1 + 1


Out[1]:
2

In [2]:
5 * 3


Out[2]:
15

Order of operations also applies:


In [3]:
13 - 8 / 4


Out[3]:
11.0

Python programs can also have multiple lines, with each line executing after the previous one.

Functions

The following example makes use of the print function. A function in Python takes arguments inside round parentheses, just as mathematical functions do. For example, we can define $f(x)=x^2$. The argument passed into the function is $x$. In Python, we can pass something into the print function to have it be shown on the screen:


In [4]:
print(7.5)
print(46)


7.5
46

Strings

We have only been working with numbers so far, but Python also has a way to work with text. We simply put single or double quotations around a string of text:


In [5]:
"Python is amazing!"


Out[5]:
'Python is amazing!'

Types

In the previous examples, we have actually been using two types of numbers: integers and decimal numbers. In Python, integers are known as ints and decimal numbers are known as floats. Pieces of text are called strings.

Calling Methods

We have already seen the use of a function, print. Another type of function, called a method, must be run, or called, on an object such as a string. To do this, we separate the object and the method we want to call with a period:


In [6]:
'Tomato'.lower()


Out[6]:
'tomato'

Variables

In Python, we can define names for values so we can store them and work with them later. We assign these names using an equals sign:


In [7]:
color = 'purple'
x = 5 * 7
print(color)
print(x + x)


purple
70

Modules and Packages

So far, we have only been using the command line to run Python code. We can also put all this code in a file with the .py extension, known as a module, then run it from the command line by running python filename.py.

Python comes with many built-in functions such as print, but we can also use functions from other modules by importing packages with the import keyword. Packages are simply directories that contain modules in them. math is a Python package that contains many useful functions and variables:


In [8]:
import math

Once we import a package or module, we can use its functions and variables the same way we would call a method on an object:


In [9]:
math.pi


Out[9]:
3.141592653589793

In [10]:
math.floor(17.8)


Out[10]:
17