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.
We can use Python to perform common arithmetic operations:
In [1]:
1 + 1
Out[1]:
In [2]:
5 * 3
Out[2]:
Order of operations also applies:
In [3]:
13 - 8 / 4
Out[3]:
Python programs can also have multiple lines, with each line executing after the previous one.
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)
In [5]:
"Python is amazing!"
Out[5]:
In the previous examples, we have actually been using two types of numbers: integers and decimal numbers. In Python, integers are known as int
s and decimal numbers are known as float
s. Pieces of text are called str
ings.
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 str
ing. To do this, we separate the object and the method we want to call with a period:
In [6]:
'Tomato'.lower()
Out[6]:
In [7]:
color = 'purple'
x = 5 * 7
print(color)
print(x + x)
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]:
In [10]:
math.floor(17.8)
Out[10]: