Introduction to Python
We’re going to use the free Anaconda Python distribution.
The Anaconda distribution includes Jupyter Lab, which is a web-based interactive development environment that is useful for doing data analysis and visualization.
Python basics:
- variables, dynamic typing
- lists
- loops
- conditions
- functions
IPython notebook from class session (.ipynb)
a = 5
print(a)
5
from math import *
print(e)
print(pi)
2.718281828459045
3.141592653589793
print(cos(pi))
-1.0
a = 5
print(a)
a = 7.2
print(a)
a = "hello"
print(a)
5
7.2
hello
things = [5, 7.2, "hello"]
print(things)
print(things[0])
print(things[1])
print(things[-1]) # negative indices!
print(things[0:2]) # slices
[5, 7.2, 'hello']
5
7.2
hello
[5, 7.2]
for a in things:
print(a)
print("blah")
5
blah
7.2
blah
hello
blah
if things[0] > 10:
print("big")
elif things[0] > 4: # else if
print("medium")
else:
print("small")
medium
print(2*3)
print(2+3)
print(2**3) # exponent
6
5
8
# print a geometric sequence
# 1, 2, 4, 8, 16, 32, ...
value = 1
for i in range(10): # [0, 1, ..., 9]
print(value)
value *= 2 # recursive definition
1
2
4
8
16
32
64
128
256
512
# explicit definition
for i in range(10):
print(2**i)
1
2
4
8
16
32
64
128
256
512
# sum from 1 to n
n = 5
total = 0
for i in range(1, n+1):
total += i
print(total)
15
# function
def sum(n):
total = 0
for i in range(1, n+1):
total += i
return total
print(sum(5))
print(sum(100))
15
5050
# fizz buzz
# print a sequence
# Fibonacci sequence
# factorial function
Python basics:
Exploratory data analysis: