Basic Python syntax (from https://www.stavros.io/tutorials/python/)
Python allows for a great deal of freedom, but does have a style guide (PEP 8) to make your code generally cleaner and more user-friendly: https://www.python.org/dev/peps/pep-0008/
Many good intro to Python resources can be found online (check them out for more detail than we can go through here) - e.g., Python tutorial: https://docs.python.org/3/tutorial/
Python code can be run in scripts, with an IDE (see Spyder), in Jupyter notebooks like this one
Jupyter Notebook:
Variable types are automatically assigned - no type declarations needed
Variable names
Printing
#Integers
my_integer = 3
print(type(my_integer))
#Floats
my_float = 1.23
print(type(my_float))
#Strings
string_1 = 'This is a string.'
string_2 = "This is also a string!"
print(type(string_1))
print(my_integer)
print('Test')
print('Test',my_integer)
print(string_1+my_integer)
print(string_1+' '+str(my_integer))
print(string_1, my_integer)
list_one = ['a','b','c','d','e','f']
print(list_one[0])
print(list_one[-1])
ages = {'Jim': 23,
'Sarah': 25,
'Tom': 30}
print(ages['Jim'])
b = 10
while b <= 20:
print (b)
b+=1
x = int(input("Please enter an integer:"))
if x < 0:
print(x,'is less than 0.')
elif x == 0:
print(x,'is 0.')
else:
print(x,'is greater than 0.')
words = ['cat', 'horse', 'chicken']
for w in words:
print(w, len(w))
python hello.py
and your name, in your command line#!/usr/bin/env python
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def main():
print('Hello there', sys.argv[1])
# Command line args are in sys.argv[1], sys.argv[2] ...
# sys.argv[0] is the script name itself and can be ignored
def string_information(string):
num_characters = len(string)
num_no_whitespace = (len(string.replace(" ", "")))
print('This string has',num_characters,'characters including \\
whitespace and',num_no_whitespace,'without whitespace.')
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()
Functions can be imported into other modules: (welcome.py can be downloaded at https://github.com/mccrayc/tutorials/blob/master/1_intro/welcome.py)
from welcome import string_information
string = 'This Is a Test'
string_information(string)
print( 3.1 + 3.6 )
print( 3.1/392 )
print( 3.1*3.2 )
print( 4**2 )
import math
from math import cos
print( cos(2*math.pi) )
print( math.sqrt(4) )
NumPy is the fundamental package for scientific computing with Python. It contains among other things
- a powerful N-dimensional array object
- sophisticated (broadcasting) functions
- tools for integrating C/C++ and Fortran code
- useful linear algebra, Fourier transform, and random number capabilities "
import numpy as np
a = np.array([[1,2,3,4],[5,6,7,8]])
print(a)
#Subtract 3 from each array element
print( a-3 )
# Get the cosine of each array element
print( np.cos(a) )
# Calculate e^x for each array element x
print (np.exp(a))
# Transpose a
print( a.T )
NumPy is a very important part of scientific Python, and forms an integral part of nearly all other scientific packages. You should look through https://docs.scipy.org/doc/numpy-dev/user/quickstart.html to get some background in how it works.
The most common plotting library with Python is currently matplotlib, which provides a MATLAB-style interface
import matplotlib.pyplot as plt
'''
This allows for an interactive figure interface within the jupyter notebook.
If you just want to show the figure without interactivity, use %matplotlib inline
'''
%matplotlib notebook
x = np.arange(0,100,0.01)
y1 = np.cos(x)
y2 = np.sin(x)
plt.plot(x,y1, label='cos(x)')
plt.plot(x,y2, label='sin(x)')
plt.axhline(y=0, color='k')
#Zoom in on the plot
plt.xlim([0,10])
#Add labels to the axes
plt.xlabel("x")
plt.ylabel("y")
#Add a title
plt.title("$sin(x)$ and $cos(x)$")
#Add a grid
plt.grid()
#Plot a basic legend
plt.legend()
plt.close()
import pandas as pd
We'll read in a CSV file that contains daily weather data for each day in 2017 from Environment and Climate Change Canada for CYUL (Montreal-Trudeau Airport)
cyul_2017 = pd.read_csv('http://www.cdmccray.com/python_tutorial/eng-daily-01012017-12312017.csv')
cyul_2017
#Set the index of the Pandas DataFrame to Date
cyul_2017.set_index('Date', inplace=True)
cyul_2017
cyul_2017.loc['2017-05-29']
Let's see what the warmest and coldest temperatures of 2017 were:
cyul_2017['Tmax'].nlargest(5)
cyul_2017['Tmin'].nsmallest(5)
First, we'll grab the individual columns we want for our x and y data
max_temps = cyul_2017['Tmax']
max_temps
plt.figure(figsize=[7,4])
plt.plot(max_temps)
Pandas has many convenience functions that allow us to quickly plot our data in a much prettier way!
plt.close()
plt.figure()
cyul_2017['Tmax'].plot(color='red', figsize=[8,5])
cyul_2017['Tmin'].plot(color='blue')
cyul_2017['Tmean'].rolling(30,min_periods=2,center=True).mean().plot(c='k', label='30-day avg. Tmean')
plt.grid()
plt.title('Montreal Daily Temperatures - 2017')
plt.ylabel('Temperature (deg C)')
plt.legend()
cyul_2017.describe()
cyul_2017[cyul_2017.Month==12].describe()
plt.close()
#######