python programming techniques eliot feibush
TRANSCRIPT
PythonProgrammingTechniques
EliotFeibush
PICSciEPrinceton Institute for
Computational Science and Engineering
Log inwithyournetID
TeachingAssistants
KyleLuiNelsonLin
VersatileVeryefficientforuser/programmer.
sample1.py
x = 0.xmax = 10.xincr = 2.
while x < xmax: # Here is a block of codey = x * xprint(x, y)x += xincr
Example
Novariabledeclaration.Nomemoryallocation.
Nocompiling,no.oor.objfilesNolinking.
Nokidding- Justrun.
MacMagnifyingglass:idle (idle.app )
Commandlinefromterminalalsopossible.______________________________________
WindowsStartMenu
Python3.6IDLE(PythonGUI)
PythonIDLE
(PythonGUI)
1.InterpreterIntegratedDevelopmentEnvironment-- idle
Everythingthataprogramcanhave:
VariablesStringsListsExpressionsImportmodules
Greatforlearning&tryingnewlinesofcode
idle
IDE – IntegratedDevelopmentEnvironmentColor-codedsyntaxStatementcompletionInterpreterretains“scope”afterprogramends
WritteninPythonwithtkinterGUImodule.
IDLEà PreferencesFont,Keys
Tryouttheinterpreter
Python 3.6.5>>> 2+35>>> a = 5.1>>> b = 6.2>>> print (a*b)31.62
help()dir()type()
>>> help() # interpretorhelp> keywords # if, else, for …help> symbols # + - = / …help> modules # math, os, syshelp> topics # USE UPPER CASE
Python Rosetta Stone
Variables
CasesensitivestartisnotthesameasStartcountisnotthesameasCountR=1/r
Startwithaletter,notanumberLongnamesOK
TypesandOperatorsint #scalarvariable,holdsasinglevaluefloatlongcomplex a=(3+4j) #type(a)
+- */%//** #Arithmeticoperators
+= #Assignmentoperators-=*=/=
< <= > >= == != #Comparisonoperators+#hasmagicoverloadabilities!
Casts
int()long()float()
hex() #stringrepresentationoct() #stringrepresentation
str() #forprintingnumbers+strings
Built-inConstantsTrue <type ‘bool’>False <type ‘bool’>None <type ‘NoneType’>
Indenting Counts!Indent4spacesoratab -- beconsistent
:atendoflineindicatesstartofcodeblockrequiresnextlinetobeindented
Codeblockendswithanoutdent
Coderunsbutnotasdesired– checkyourindents
Program
LoopsConditionals, ControlFunctions
Keywords
Controlif else elif
while break continue
and or not
>>> help()help > keywords
idle:Fileà NewFileSavecommand-sRunà RunModule F5key
ProgrammingExercise
Writeapythonprogramthatconvertsdegreestoradiansfor:
0,10,20,30,...180degrees
editandsave:deg.pyRunF5: deg.py
radians=degrees*3.14 /180.print(degrees,radians)
x = 0.xmax = 10.xincr = 2.
while x < xmax:y = x * xprint(x, y)x += xincr
DebuggingTip
IDLEshellretainsvariablesinscopeafterrunningprogram:
dir()
print(degree)
Comments
inlinetextafter#isignored#canbeinanycolumn
Textwithintriplequotes“”” This is a multi-linecomment that will becompiled to a string but will not execute anything.It is code so it must conformto indenting ”””
sample2.py
s = “shrubbery”print(s)
len(s)
StringsSequenceofcharacterssuchass=“abcdefg”Indexedwith[]startingat[0]
s[0]isa,s[1]isb
s[-1]referstolastcharacterinstring.Negativeindexingstartsatlastcharacter.
Uses[p:q]forstringslicing.s[3:]evaluatedas“defg”s[:3] evaluatedas“abc”uptobutnot3s[1:-2] evaluatedas“bcde”
uptobutnotincluding-2
StringConcatenation
first = ‘John’last = ‘Cleese’
full = first + “ “ + last
sp = “ “full = first + sp + last
+OperatorisOperand“Aware”
>>>“water” + “fall” #concatenate
>>>3 + 5 #addition________________________________________>>>3 + “George” #unsupportedtype
>>>“George” + 3 #TypeError
Printingpi = 3.14159print (‘The answer is ‘ + str(pi))
#castfloattostringtoavoidTypeError
TheImmutableString
Can’treplacecharactersinastring.
s = “abcd”
s[1] = “g” Objectdoesnotsupportitemassignment
s = “agcd” #re-assignentirestring
AutomaticMemoryManagment
malloc() realloc() free()char name[32]
name = “as long as you want”
len(name) #len()functionispartof__builtins__
Conditionalsa = 3
if a > 0:print (“a is positive”)
elif a < 0:print( “a is negative”)
else:print (“a = 0”)
StringExercise
Degreestoradians:PrintcolumntitlesRightaligndegreevaluesLimitradiansto7characters
Reminder:len(s)
strUndertheHoodstr - isaClass!Notjustamemoryareaofcharacters
ObjectorientedprogrammingEncapsulateddataandmethodsUsethedot.toaddressmethodsanddata
a = “hello”a.upper() #returns“HELLO”
type(a)dir(str)help(str)
hiddenmethodsstartwith__
>>>help()help>topicshelp>STRINGMETHODS
Mathmodule
import mathdir(math)
math.sqrt(x)math.sin(x)math.cos(x)
from math import *dir()
sqrt(x)
from math import pidir()
print pi
import from as
Keywords forInclusion
importmathExercise
Degreestoradiansandnowcosine:Usemath.pifordefinedconstantUsemath.cos(radian)tocomputecosinePrintcosinein3rd column
Aligncosinetodecimalpoint(Donottruncatethecosine)
Data Structures Resemble arrays in other languages
List[] #orderedsequenceofstuff
Tuple() #n-tuple,immutable
Dictionary{} #key– valuepairs
Lists[]Indexedfrom[0]Lastindexis[-1]orlength- 1
Classobjectwithitsownmethods,e.g..append().sort()
Magicsliceoperator:Magiciter() function actually__iter__()
min()max()arebuiltins
DeclareaList
x = [14, 23, 34, 42, 50, 59]
x.append(66) #worksinplace,noreturn
Identifythesequence?x.append(“SpringSt”,“CanalSt”)
x[0] = 12 #listismutable,canreplacevaluesx = [] #canappendtoemptylistx = list()
Listmethodsappend()extend()insert()remove()sort() #inplace,doesnotreturnanewlistreverse() #inplaceindex()count()
cList = aList + bList #concatenatelists
range()Functionrange(stop) # assumes start=0 and incr=1range(start, stop) # assumes incr=1range(start, stop, incr)
Returnssequence ofintegers,upto,butnotincludingstop.Python2returnsalist.
Python3returnsa"rangeclass"tosavememory.Bothgiveyouaniterable sequence.
range()isabuilt-infunction:dir(__builtins__)
Keywords Loopingwithrange()
for in
for i in range(10):
for i in dayList:
ListTechniques
d = list(range(4)) #[0,1,2,3]d = [0] * 4 #[0,0,0,0]
d = [ -1 for x in range(4) ] #[-1,-1,-1,-1]
ListComprehension
ListsExercise
Degreestoradians,cosines,andnowlists:Create alistofradiansandalistofcosinesPrintthelistsUsearange()loopinsteadofwhile
PlotExerciseDegreestoradians,cosines,lists,nowplot:Plotacurve:xaxis:radians,yaxis:cosines
import matplotlib.pyplot as plt
plt.plot(radiansL, cosinesL)
plt.show() # displays on screen
matplotlib+ LaTeXimport matplotlib.pyplot as plt
plt.rc(“text”, usetex=True)# set config to draw text with Tex
plt.xlabel( r”\textbf{Time}” )#drawxlabel“Time”inboldfont#compareto:plt.xlabel(“Time”)
s = r”\n” # raw string has \n, not linefeedlatex.pyexample- requireslatexinstallation
del keyword
del a[3] #deleteselement atindex3
del a[2:4] #deleteselement2and3#listslicing
del a #deletesentirelist.aisgone.
Unpackalistintovariables
name = [“Abe”, “Lincoln”]
first, last = name# multiple variables on left side of =# number of variables must be len(name)
ListofLists
d = [ [0]*4 for y in range(3) ]
[[0,0,0,0],[0,0,0,0],[0,0,0,0]
]
d[2][0]=5[
[0,0,0,0],[0,0,0,0],[5,0,0,0]
]
N-dimensionalArraysimport numpy
ndarray class – optimized to be very fast.Integrated with matplotlib for graphing.
princeton.edu/~efeibushPythonProgrammingmini-course
numpynumpy2016.pdf
49
numpy.arange()
Note:arangecanusefloatsforinterval&step
import numpyradA = numpy.arange(1.5, 2.5, .1)
#Returnsnumpyarrayofevenlyspacedfloats#min,max,step
for x in radA: #caniterateonnumpyarray
numpy.linspace()
Note:linspacecanusefloatsforintervalintegerfornumberofsteps
import numpya = numpy.linspace(1.5, 2.5, 11)
#Returnsnumpyarrayofevenlyspacedfloats#min,max,numberofsteps
a = list(a) # cast array to list
for x in a:
pythonRunsyourprogram2.CommandLineversion
python sample1.py
sample1.pysourcecodeisrundirectlyinsteadofcompile,link,run
No.objnor.ofilesofcompiledcodeNo.exenora.outofexecutablecode
python -i exdeg.py
CommandLineArguments
import sysprint (sys.argv)
sys.argvisalistsys.argv[0]hasthenameofthepythonfile.Subsequentlocationshavecommandlineargs.Doesnotapplyininterpreter.
>>>help(sys)
ShellScriptingimport os
fileL = [] #setupalist
for f in os.listdir("."):if f.endswith(".py"):
print( f )fileL.append(f)
fileL.sort() #listfunction,sortinplace
print (fileL)
#muchbettertexthandlingthancshorbash;shellindependent
import subprocess #Advanced#thenusethePopenclassforrunningprograms
#!/bin/csh
foreach file(*.py)echo$fileend
DefiningaFunctionBlockofcodeseparatefrommain.
Definefunctionbeforecallingit.
def myAdd(a, b): #definebeforecallingreturn a + b
p = 25 #mainsectionofcodeq = 30
r = myAdd(p, q) #casesensitive
Keywords
Functions(methods,subroutines)defreturn
DefineaFunctionExercise
Degreestoradians,cosines,lists,nowfunction:Formattheradiansusingafunctioncall
import
import math #knowswheretofindit
import syssys.path.append(“/Users/efeibush/spline”)import cubic.py #importyourowncode
reload– debuggingyourownmodulefromtheinterpreter
n-Tuple()ImmutableListSavessomememoryCannotbemodifiedwhenpassedtosubroutine
aTuple = tuple(aList) #Createfromalist#Noappend,noassignment;OKtoextractslice
cTuple = aTuple + bTuple #OKtoconcatenate
print aTuple[0] #indexusingbrackets
Dictionary { }Key:ValueLookuptableIndexbykey-- Anyhashable(immutable) typeprint d[key] #printsvalueforspecifiedkey
Orderofkey:valuepairsisnotguaranteed.Goodforcommandlinearguments
namelistfiles,nicknames,etc.d[key] = value #toaddakey-valuepair
suchasd[“New Jersey”] = “Trenton”
Dictionarymethodsd = { }d = dict()
eDict.update(gDict) # combine dictionaries
del eDict[key]
if key in eDict:print (eDict[key])
d.keys() #returnssetofallkeysd.items() #returnssetofall key:valuepairsastuples
ReadaTextFilegFile = open("myfile.txt”, “r”) # built-in function
for j in gFile: #pythonmagic:textfileiteratesonlinesprint j #printeachline
gFile.close()
seereadsplit.pystr.split().split()methodparsesalineoftextintolistofwords
WriteaTextFilef = open("myfile.txt", "w")
#openisabuilt-infunctiona = 1b = 2
f.write("Here is line " + str(a) + "\n");f.write("Next is line " + str(b) + "\n");
f.close()#.write()and.close()arefileobjectmethods
tryexceptfinally
Keywords forExceptionHandling
Summary– ElementsofPython
Scalar variables, operatorsStrings - Class with methodsList [ ] tuple ( ) dictionary { }ControlComments, indentingdef your own functionsimport modules – use functionsPlottingText File I/O
Built-inClassesstr, list, tuple, dict, file
dir(str)help(str)
hiddenmethodsstartwith__
Built-inFunctionslen()range() #returnsalist[]ofintegerstype()input() #readfromstandardinput
#Python2:raw_input()print()open() #fileI/Ohelp() #interpreter
abs() round() complex()min() max() sum() pow()
dir()dir(__builtins__)e.g.help(input)
Interpreterhelp()
>>> help() #gointohelpmodehelp>
keywordssymbolstopics modules
#entertopicUPPERCASEq
>>>
Pythonatprinceton.edussh nobel.princeton.edu
% which python
/usr/bin/pythonversion2.7.5
module load anaconda3/4.4.0python 3.6
nobeldellatiger
tigressdata
More Info & Resourcespython.orgdocs.python.org
princeton.edu/~efeibush/python“notes3”folderhasexercises
PrincetonUniversityPythonCommunityprincetonpy.com
PICSciE walk-inhelpsessions:Lewis347Tuesday10:00– 11:00amThursday2– 3pm
Whereto?Anaconda distribution of python
matplotlib – draw graphsnumpy – arrays & math functions scipy – algorithms & math toolsPIL - Image ProcessingMultiprocessingPycuda à GPU, CUDAGUI – Tkinter, pyqt, wxpythonVisualization toolkit – python scripting
ArtContest
Writeapgm(world’ssimplest)imagefile:Replacemylineforagradientwithyourcodetomakeanimage.
ChangemaxIntensitytoyourscale.
Displayyourpicture:python pgmdisplay.py
ReadinganetCDFFile
Structured,scientificdatafileformatCanreadfromURL
scipy– netcdf_fileclassforread/writenumpy– multi-dimensionaldataarrays