intro to python programming
play

Intro to Python programming Dept. of Informatics, Univ. of Oslo May - PDF document

5mm. Numerical Python Hans Petter Langtangen Simula Research Laboratory Intro to Python programming Dept. of Informatics, Univ. of Oslo May 2010 Numerical Python p.1/397 Intro to Python programming p.2/397 Make sure you have the


  1. 5mm. Numerical Python Hans Petter Langtangen Simula Research Laboratory Intro to Python programming Dept. of Informatics, Univ. of Oslo May 2010 Numerical Python – p.1/397 Intro to Python programming – p.2/397 Make sure you have the software Material associated with these slides Python version 2.5 These slides have a companion book: Scripting in Computational Science , 3rd edition, Numerical Python ( numpy ) Texts in Computational Science and Engineering, Gnuplot program, Python Gnuplot module Springer, 2008 SciTools All examples can be downloaded as a tarfile For multi-language programming: gcc, g++, g77 http://folk.uio.no/hpl/scripting/TCSE3-3rd-examples.tar.gz For GUI programming: Tcl/Tk, Pmw Software associated with the book and slides: SciTools Some Python modules are handy: IPython, Epydoc, ... http://code.google.com/p/scitools/ Intro to Python programming – p.3/397 Intro to Python programming – p.4/397 Installing TCSE3-3rd-examples.tar.gz Scientific Hello World script Pack TCSE3-3rd-examples.tar.gz out in a directory and All computer languages intros start with a program that prints let scripting be an environment variable pointing to the top "Hello, World!" to the screen directory: Scientific computing extension: read a number, compute its sine tar xvzf TCSE3-3rd-examples.tar.gz value, and print out export scripting=‘pwd‘ The script, called hw.py, should be run like this: All paths in these slides are given relative to scripting , e.g., python hw.py 3.4 src/py/intro/hw.py is reached as or just (Unix) $scripting/src/py/intro/hw.py ./hw.py 3.4 Output: Hello, World! sin(3.4)=-0.255541102027 Intro to Python programming – p.5/397 Intro to Python programming – p.6/397 Purpose of this script The code Demonstrate File hw.py: how to get input from the command line #!/usr/bin/env python # load system and math module: how to call a math function like sin(x) import sys, math how to work with variables # extract the 1st command-line argument: r = float(sys.argv[1]) how to print text and numbers s = math.sin(r) print "Hello, World! sin(" + str(r) + ")=" + str(s) Make the file executable (on Unix): chmod a+rx hw.py Intro to Python programming – p.7/397 Intro to Python programming – p.8/397

  2. Alternative print statements Comments The first line specifies the interpreter of the script Desired output: (here the first python program in your path) Hello, World! sin(3.4)=-0.255541102027 python hw.py 1.4 # first line is treated as comment ./hw.py 1.4 # first line is used to specify an interpreter String concatenation: print "Hello, World! sin(" + str(r) + ")=" + str(s) Even simple scripts must load modules: import sys, math printf-like statement: print "Hello, World! sin(%g)=%g" % (r,s) Numbers and strings are two different types: r = sys.argv[1] # r is string Variable interpolation: s = math.sin(float(r)) print "Hello, World! sin(%(r)g)=%(s)g" % vars() # sin expects number, not string r # s becomes a floating-point number Intro to Python programming – p.9/397 Intro to Python programming – p.10/397 printf format strings Strings in Python %d : integer Single- and double-quoted strings work in the same way %5d : integer in a field of width 5 chars %-5d : integer in a field of width 5 chars, s1 = "some string with a number %g" % r but adjusted to the left s2 = ’some string with a number %g’ % r # = s1 %05d : integer in a field of width 5 chars, padded with zeroes from the left Triple-quoted strings can be multi line with embedded newlines: %g : float variable in %f or %g notation text = """ %e : float variable in scientific notation large portions of a text %11.3e : float variable in scientific notation, with 3 decimals, field of width 11 chars can be conveniently placed %5.1f : float variable in fixed decimal notation, inside triple-quoted strings with one decimal, field of width 5 chars (newlines are preserved)""" %.3f : float variable in fixed decimal form, with three decimals, field of min. width Raw strings, where backslash is backslash: %s : string %-20s : string in a field of width 20 chars, s3 = r’\(\s+\.\d+\)’ and adjusted to the left # with ordinary string (must quote backslash): s3 = ’\\(\\s+\\.\\d+\\)’ Intro to Python programming – p.11/397 Intro to Python programming – p.12/397 Where to find Python info New example: reading/writing data files Make a bookmark for $scripting/doc.html Tasks: Follow link to Index to Python Library Reference Read (x,y) data from a two-column file (complete on-line Python reference) Transform y values to f(y) Click on Python keywords, modules etc. Write (x,f(y)) to a new file Online alternative: pydoc , e.g., pydoc math What to learn: pydoc lists all classes and functions in a module How to open, read, write and close files Alternative: Python in a Nutshell (or Beazley’s textbook) How to write and call a function Recommendation: use these slides and associated book together How to work with arrays (lists) with the Python Library Reference, and learn by doing exercises File: src/py/intro/datatrans1.py Intro to Python programming – p.13/397 Intro to Python programming – p.14/397 Reading input/output filenames Exception handling Usage: What if the user fails to provide two command-line arguments? ./datatrans1.py infilename outfilename Python aborts execution with an informative error message A good alternative is to handle the error manually inside the Read the two command-line arguments: program code: input and output filenames try: infilename = sys.argv[1] infilename = sys.argv[1] outfilename = sys.argv[2] outfilename = sys.argv[2] except: Command-line arguments are in sys.argv[1:] # try block failed, # we miss two command-line arguments sys.argv[0] is the name of the script print ’Usage:’, sys.argv[0], ’infile outfile’ sys.exit(1) This is the common way of dealing with errors in Python, called exception handling Intro to Python programming – p.15/397 Intro to Python programming – p.16/397

  3. Open file and read line by line Defining a function import math Open files: def myfunc(y): ifile = open( infilename, ’r’) # r for reading if y >= 0.0: ofile = open(outfilename, ’w’) # w for writing return y**5*math.exp(-y) afile = open(appfilename, ’a’) # a for appending else: return 0.0 Read line by line: # alternative way of calling module functions for line in ifile: # (gives more math-like syntax in this example): # process line from math import * def myfunc(y): Observe: blocks are indented; no braces! if y >= 0.0: return y**5*exp(-y) else: return 0.0 Intro to Python programming – p.17/397 Intro to Python programming – p.18/397 Data transformation loop Alternative file reading Input file format: two columns with numbers This construction is more flexible and traditional in Python (and a bit strange...): 0.1 1.4397 0.2 4.325 while 1: 0.5 9.0 line = ifile.readline() # read a line if not line: break # end of file: jump out of loop Read a line with x and y, transform y, write x and f(y): # process line for line in ifile: i.e., an ’infinite’ loop with the termination criterion inside the loop pair = line.split() x = float(pair[0]); y = float(pair[1]) fy = myfunc(y) # transform y value ofile.write(’%g %12.5e\n’ % (x,fy)) Intro to Python programming – p.19/397 Intro to Python programming – p.20/397 Loading data into lists Loop over list entries Read input file into list of lines: For-loop in Python: lines = ifile.readlines() for i in range(start,stop,inc): ... for j in range(stop): Now the 1st line is lines[0] , the 2nd is lines[1] , etc. ... Store x and y data in lists: generates # go through each line, i = start, start+inc, start+2*inc, ..., stop-1 # split line into x and y columns j = 0, 1, 2, ..., stop-1 x = []; y = [] # store data pairs in lists x and y Loop over (x,y) values: for line in lines: xval, yval = line.split() ofile = open(outfilename, ’w’) # open for writing x.append(float(xval)) for i in range(len(x)): y.append(float(yval)) fy = myfunc(y[i]) # transform y value ofile.write(’%g %12.5e\n’ % (x[i], fy)) ofile.close() See src/py/intro/datatrans2.py for this version Intro to Python programming – p.21/397 Intro to Python programming – p.22/397 Running the script More about headers Method 1: write just the name of the scriptfile: In method 1, the interpreter to be used is specified in the first line ./datatrans1.py infile outfile Explicit path to the interpreter: # or #!/usr/local/bin/python datatrans1.py infile outfile or perhaps your own Python interpreter: if . (current working directory) or the directory containing #!/home/hpl/projects/scripting/Linux/bin/python datatrans1.py is in the path Method 2: run an interpreter explicitly: Using env to find the first Python interpreter in the path: python datatrans1.py infile outfile #!/usr/bin/env python Use the first python program found in the path This works on Windows too (method 1 requires the right assoc/ftype bindings for .py files) Intro to Python programming – p.23/397 Intro to Python programming – p.24/397

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend