74
Python Programming Techniques Eliot Feibush PICSciE Princeton Institute for Computational Science and Engineering Log in with your netID

Python Programming Techniques Eliot Feibush

  • Upload
    others

  • View
    9

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Python Programming Techniques Eliot Feibush

PythonProgrammingTechniques

EliotFeibush

PICSciEPrinceton Institute for

Computational Science and Engineering

Log inwithyournetID

Page 2: Python Programming Techniques Eliot Feibush

TeachingAssistants

KyleLuiNelsonLin

Page 3: Python Programming Techniques Eliot Feibush

VersatileVeryefficientforuser/programmer.

Page 4: Python Programming Techniques Eliot Feibush

sample1.py

x = 0.xmax = 10.xincr = 2.

while x < xmax: # Here is a block of codey = x * xprint(x, y)x += xincr

Page 5: Python Programming Techniques Eliot Feibush

Example

Novariabledeclaration.Nomemoryallocation.

Nocompiling,no.oor.objfilesNolinking.

Nokidding- Justrun.

Page 6: Python Programming Techniques Eliot Feibush

MacMagnifyingglass:idle (idle.app )

Commandlinefromterminalalsopossible.______________________________________

WindowsStartMenu

Python3.6IDLE(PythonGUI)

PythonIDLE

(PythonGUI)

Page 7: Python Programming Techniques Eliot Feibush

1.InterpreterIntegratedDevelopmentEnvironment-- idle

Everythingthataprogramcanhave:

VariablesStringsListsExpressionsImportmodules

Greatforlearning&tryingnewlinesofcode

Page 8: Python Programming Techniques Eliot Feibush

idle

IDE – IntegratedDevelopmentEnvironmentColor-codedsyntaxStatementcompletionInterpreterretains“scope”afterprogramends

WritteninPythonwithtkinterGUImodule.

IDLEà PreferencesFont,Keys

Page 9: Python Programming Techniques Eliot Feibush

Tryouttheinterpreter

Python 3.6.5>>> 2+35>>> a = 5.1>>> b = 6.2>>> print (a*b)31.62

Page 10: Python Programming Techniques Eliot Feibush

help()dir()type()

>>> help() # interpretorhelp> keywords # if, else, for …help> symbols # + - = / …help> modules # math, os, syshelp> topics # USE UPPER CASE

Python Rosetta Stone

Page 11: Python Programming Techniques Eliot Feibush

Variables

CasesensitivestartisnotthesameasStartcountisnotthesameasCountR=1/r

Startwithaletter,notanumberLongnamesOK

Page 12: Python Programming Techniques Eliot Feibush

TypesandOperatorsint #scalarvariable,holdsasinglevaluefloatlongcomplex a=(3+4j) #type(a)

+- */%//** #Arithmeticoperators

+= #Assignmentoperators-=*=/=

< <= > >= == != #Comparisonoperators+#hasmagicoverloadabilities!

Page 13: Python Programming Techniques Eliot Feibush

Casts

int()long()float()

hex() #stringrepresentationoct() #stringrepresentation

str() #forprintingnumbers+strings

Page 14: Python Programming Techniques Eliot Feibush

Built-inConstantsTrue <type ‘bool’>False <type ‘bool’>None <type ‘NoneType’>

Page 15: Python Programming Techniques Eliot Feibush

Indenting Counts!Indent4spacesoratab -- beconsistent

:atendoflineindicatesstartofcodeblockrequiresnextlinetobeindented

Codeblockendswithanoutdent

Coderunsbutnotasdesired– checkyourindents

Page 16: Python Programming Techniques Eliot Feibush

Program

LoopsConditionals, ControlFunctions

Page 17: Python Programming Techniques Eliot Feibush

Keywords

Controlif else elif

while break continue

and or not

>>> help()help > keywords

Page 18: Python Programming Techniques Eliot Feibush

idle:Fileà NewFileSavecommand-sRunà RunModule F5key

Page 19: Python Programming Techniques Eliot Feibush

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

Page 20: Python Programming Techniques Eliot Feibush

DebuggingTip

IDLEshellretainsvariablesinscopeafterrunningprogram:

dir()

print(degree)

Page 21: Python Programming Techniques Eliot Feibush

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 ”””

Page 22: Python Programming Techniques Eliot Feibush

sample2.py

s = “shrubbery”print(s)

len(s)

Page 23: Python Programming Techniques Eliot Feibush

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

Page 24: Python Programming Techniques Eliot Feibush

StringConcatenation

first = ‘John’last = ‘Cleese’

full = first + “ “ + last

sp = “ “full = first + sp + last

Page 25: Python Programming Techniques Eliot Feibush

+OperatorisOperand“Aware”

>>>“water” + “fall” #concatenate

>>>3 + 5 #addition________________________________________>>>3 + “George” #unsupportedtype

>>>“George” + 3 #TypeError

Page 26: Python Programming Techniques Eliot Feibush

Printingpi = 3.14159print (‘The answer is ‘ + str(pi))

#castfloattostringtoavoidTypeError

Page 27: Python Programming Techniques Eliot Feibush

TheImmutableString

Can’treplacecharactersinastring.

s = “abcd”

s[1] = “g” Objectdoesnotsupportitemassignment

s = “agcd” #re-assignentirestring

Page 28: Python Programming Techniques Eliot Feibush

AutomaticMemoryManagment

malloc() realloc() free()char name[32]

name = “as long as you want”

len(name) #len()functionispartof__builtins__

Page 29: Python Programming Techniques Eliot Feibush

Conditionalsa = 3

if a > 0:print (“a is positive”)

elif a < 0:print( “a is negative”)

else:print (“a = 0”)

Page 30: Python Programming Techniques Eliot Feibush

StringExercise

Degreestoradians:PrintcolumntitlesRightaligndegreevaluesLimitradiansto7characters

Reminder:len(s)

Page 31: Python Programming Techniques Eliot Feibush

strUndertheHoodstr - isaClass!Notjustamemoryareaofcharacters

ObjectorientedprogrammingEncapsulateddataandmethodsUsethedot.toaddressmethodsanddata

a = “hello”a.upper() #returns“HELLO”

type(a)dir(str)help(str)

hiddenmethodsstartwith__

>>>help()help>topicshelp>STRINGMETHODS

Page 32: Python Programming Techniques Eliot Feibush

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

Page 33: Python Programming Techniques Eliot Feibush

import from as

Keywords forInclusion

Page 34: Python Programming Techniques Eliot Feibush

importmathExercise

Degreestoradiansandnowcosine:Usemath.pifordefinedconstantUsemath.cos(radian)tocomputecosinePrintcosinein3rd column

Aligncosinetodecimalpoint(Donottruncatethecosine)

Page 35: Python Programming Techniques Eliot Feibush

Data Structures Resemble arrays in other languages

List[] #orderedsequenceofstuff

Tuple() #n-tuple,immutable

Dictionary{} #key– valuepairs

Page 36: Python Programming Techniques Eliot Feibush

Lists[]Indexedfrom[0]Lastindexis[-1]orlength- 1

Classobjectwithitsownmethods,e.g..append().sort()

Magicsliceoperator:Magiciter() function actually__iter__()

min()max()arebuiltins

Page 37: Python Programming Techniques Eliot Feibush

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()

Page 38: Python Programming Techniques Eliot Feibush

Listmethodsappend()extend()insert()remove()sort() #inplace,doesnotreturnanewlistreverse() #inplaceindex()count()

cList = aList + bList #concatenatelists

Page 39: Python Programming Techniques Eliot Feibush

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__)

Page 40: Python Programming Techniques Eliot Feibush

Keywords Loopingwithrange()

for in

for i in range(10):

for i in dayList:

Page 41: Python Programming Techniques Eliot Feibush

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

Page 42: Python Programming Techniques Eliot Feibush

ListsExercise

Degreestoradians,cosines,andnowlists:Create alistofradiansandalistofcosinesPrintthelistsUsearange()loopinsteadofwhile

Page 43: Python Programming Techniques Eliot Feibush

PlotExerciseDegreestoradians,cosines,lists,nowplot:Plotacurve:xaxis:radians,yaxis:cosines

import matplotlib.pyplot as plt

plt.plot(radiansL, cosinesL)

plt.show() # displays on screen

Page 44: Python Programming Techniques Eliot Feibush

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

Page 45: Python Programming Techniques Eliot Feibush
Page 46: Python Programming Techniques Eliot Feibush

del keyword

del a[3] #deleteselement atindex3

del a[2:4] #deleteselement2and3#listslicing

del a #deletesentirelist.aisgone.

Page 47: Python Programming Techniques Eliot Feibush

Unpackalistintovariables

name = [“Abe”, “Lincoln”]

first, last = name# multiple variables on left side of =# number of variables must be len(name)

Page 48: Python Programming Techniques Eliot Feibush

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]

]

Page 49: Python Programming Techniques Eliot Feibush

N-dimensionalArraysimport numpy

ndarray class – optimized to be very fast.Integrated with matplotlib for graphing.

princeton.edu/~efeibushPythonProgrammingmini-course

numpynumpy2016.pdf

49

Page 50: Python Programming Techniques Eliot Feibush

numpy.arange()

Note:arangecanusefloatsforinterval&step

import numpyradA = numpy.arange(1.5, 2.5, .1)

#Returnsnumpyarrayofevenlyspacedfloats#min,max,step

for x in radA: #caniterateonnumpyarray

Page 51: Python Programming Techniques Eliot Feibush

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:

Page 52: Python Programming Techniques Eliot Feibush

pythonRunsyourprogram2.CommandLineversion

python sample1.py

sample1.pysourcecodeisrundirectlyinsteadofcompile,link,run

No.objnor.ofilesofcompiledcodeNo.exenora.outofexecutablecode

python -i exdeg.py

Page 53: Python Programming Techniques Eliot Feibush

CommandLineArguments

import sysprint (sys.argv)

sys.argvisalistsys.argv[0]hasthenameofthepythonfile.Subsequentlocationshavecommandlineargs.Doesnotapplyininterpreter.

>>>help(sys)

Page 54: Python Programming Techniques Eliot Feibush

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

Page 55: Python Programming Techniques Eliot Feibush

DefiningaFunctionBlockofcodeseparatefrommain.

Definefunctionbeforecallingit.

def myAdd(a, b): #definebeforecallingreturn a + b

p = 25 #mainsectionofcodeq = 30

r = myAdd(p, q) #casesensitive

Page 56: Python Programming Techniques Eliot Feibush

Keywords

Functions(methods,subroutines)defreturn

Page 57: Python Programming Techniques Eliot Feibush

DefineaFunctionExercise

Degreestoradians,cosines,lists,nowfunction:Formattheradiansusingafunctioncall

Page 58: Python Programming Techniques Eliot Feibush

import

import math #knowswheretofindit

import syssys.path.append(“/Users/efeibush/spline”)import cubic.py #importyourowncode

reload– debuggingyourownmodulefromtheinterpreter

Page 59: Python Programming Techniques Eliot Feibush

n-Tuple()ImmutableListSavessomememoryCannotbemodifiedwhenpassedtosubroutine

aTuple = tuple(aList) #Createfromalist#Noappend,noassignment;OKtoextractslice

cTuple = aTuple + bTuple #OKtoconcatenate

print aTuple[0] #indexusingbrackets

Page 60: Python Programming Techniques Eliot Feibush

Dictionary { }Key:ValueLookuptableIndexbykey-- Anyhashable(immutable) typeprint d[key] #printsvalueforspecifiedkey

Orderofkey:valuepairsisnotguaranteed.Goodforcommandlinearguments

namelistfiles,nicknames,etc.d[key] = value #toaddakey-valuepair

suchasd[“New Jersey”] = “Trenton”

Page 61: Python Programming Techniques Eliot Feibush

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

Page 62: Python Programming Techniques Eliot Feibush

ReadaTextFilegFile = open("myfile.txt”, “r”) # built-in function

for j in gFile: #pythonmagic:textfileiteratesonlinesprint j #printeachline

gFile.close()

seereadsplit.pystr.split().split()methodparsesalineoftextintolistofwords

Page 63: Python Programming Techniques Eliot Feibush

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

Page 64: Python Programming Techniques Eliot Feibush

tryexceptfinally

Keywords forExceptionHandling

Page 65: Python Programming Techniques Eliot Feibush

Summary– ElementsofPython

Scalar variables, operatorsStrings - Class with methodsList [ ] tuple ( ) dictionary { }ControlComments, indentingdef your own functionsimport modules – use functionsPlottingText File I/O

Page 66: Python Programming Techniques Eliot Feibush

Built-inClassesstr, list, tuple, dict, file

dir(str)help(str)

hiddenmethodsstartwith__

Page 67: Python Programming Techniques Eliot Feibush

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)

Page 68: Python Programming Techniques Eliot Feibush

Interpreterhelp()

>>> help() #gointohelpmodehelp>

keywordssymbolstopics modules

#entertopicUPPERCASEq

>>>

Page 69: Python Programming Techniques Eliot Feibush

Pythonatprinceton.edussh nobel.princeton.edu

% which python

/usr/bin/pythonversion2.7.5

module load anaconda3/4.4.0python 3.6

nobeldellatiger

tigressdata

Page 70: Python Programming Techniques Eliot Feibush

More Info & Resourcespython.orgdocs.python.org

princeton.edu/~efeibush/python“notes3”folderhasexercises

PrincetonUniversityPythonCommunityprincetonpy.com

PICSciE walk-inhelpsessions:Lewis347Tuesday10:00– 11:00amThursday2– 3pm

Page 71: Python Programming Techniques Eliot Feibush

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

Page 72: Python Programming Techniques Eliot Feibush
Page 73: Python Programming Techniques Eliot Feibush

ArtContest

Writeapgm(world’ssimplest)imagefile:Replacemylineforagradientwithyourcodetomakeanimage.

ChangemaxIntensitytoyourscale.

Displayyourpicture:python pgmdisplay.py

Page 74: Python Programming Techniques Eliot Feibush

ReadinganetCDFFile

Structured,scientificdatafileformatCanreadfromURL

scipy– netcdf_fileclassforread/writenumpy– multi-dimensionaldataarrays