Essentials for Scientific Computing: Introduction to Python Day 11 & 12
|
|
- Hector Washington
- 6 years ago
- Views:
Transcription
1 Essentials for Scientific Computing: Introduction to Python Day 11 & 12 Ershaad Ahamed TUE-CMS, JNCASR May Conditionals 1.1 if Construct In python blocks of code are created by indentation. That means code within a block are separated from others by an equal amount of spaces/tabs on the left side. The standard ifelifelse construct. myint = 234 if myint % 2 == 0: print "Multiple of 2" elif myint % 3 == 0: print "Multiple of 3" elif myint % 4 == 0: print "Multiple of 4" else: print "Not multiple of 2, 3 or 4" Multiple of 2 If the condition for the first if evaluates to True, then the statements within that block are executed. Otherwise the condition for each of the elif statements is evaluated until one of them evaluates to True. If none of them are True then the else block is executed. The elif and else blocks are optional. 2 Looping 2.1 The for Loop In python the for loop actually loops over values in a sequence. A common way to loop over a sequence of integers is to use the range() function which returns a list of integers. 1
2 seq = range(10) print seq [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for i in range(5): print "Current value of i is ", i print "twice that is", i*2 Current value of i is 0 twice that is 0 Current value of i is 1 twice that is 2 Current value of i is 2 twice that is 4 Current value of i is 3 twice that is 6 Current value of i is 4 twice that is 8 We can also loop over a list of tuples and use sequence unpacking. mylist = [("name","ershaad"), ("surname","basheer"), ("dept.", "TUE-CMS")] for i in mylist: print i ( name, ershaad ) ( surname, basheer ) ( dept., TUE-CMS ) for field, value in mylist: print field, " has value ", value name has value ershaad surname has value basheer dept. has value TUE-CMS Since strings are a sequence type, we can loop over them too. mystring = "JNCASR" for alph in mystring: print alph J N C A S R 2
3 2.2 while loop The while loop continues looping as long as a condition is true. In the while loop below, the loop continues as long as count is less than 5. count = 0 while count < 5: print count count = count break and continue The break statement will terminate the loop within which it is enclosed and the continue statement will cause the loop to skip to the next iteration. while True: inp = raw_input("enter word :") if inp == "end" or inp == "End": break elif inp == "skip" or inp == "Skip": continue else: print inp Enter word :World World Enter word :end end Enter word :word word Enter word :skip Enter word :End The loop above reads input from the terminal and writes the string that it read. It continues until the user enters the work end or End. If the user enters the word skip or Skip, the program does not print the string and instead proceeds to read new input. raw input() is a python built-in function that reads input from the keyboard and returns it as a string. The python keyword True is a built-in boolean type which always evaluates to a true value. In each iteration of the loop, input from the user is read and compared with the string End or end. If the input matches, the break keyword causes python to exit from the loop which ends the program. If the input string does not match, then it proceeds to check if it matches the string skip or Skip. If it matches, the continue 3
4 statement is executed which causes python to skip all the remaining statements within the while loop and immediately begin with the next iteration of the loop. If the input does not match either of the conditions, the else block is executed which contains the statement to print the input string Membership Testing The python in keyword can be used to check if a value is a member of a sequence type. The following examples can make this clear. mylist = ["orange", "mango", 23, 33] if "orange" in mylist: print "YES" YES if "apple" in mylist: print "YES" mystring = "statehouse" if "teh" in mystring: print "YES" YES if "the" in mystring: print "YES" 3 Python Scripts In the same way as shell scripts, python code can be placed in a file and executed. Python program files are usually named with a.py extension. In order to make python files directly executable from the shell, we add executable permissions to the file with chmod u+x filename.py and set the first line of the script to be 4 Functions A function allows us to group code into a callable subroutine. Below is a function that replaces all occurrences of character fchar to tchar in string srcstr and returns the resulting string. def subst(fchar, tchar, srcstr): result = "" for char in srcstr: if char == fchar: 4
5 result += tchar else: result += char return result mystring = "helloworld" mystring = subst( o, x, mystring) print mystring A function is defined using the def keyword follwed by the function name, and parameters in parenthesis. Unline C and FORTRAN, only parameter names are necessary and not types. Within the function, the variable name result is bound to an empty string. The for loop iterates over each character in srcstr while assigning it to the variable char. If char is not the character fchar that needs to be replaced, then char is appended to the end of result, otherwise, the character tchar is appended to result 5 Modules Below is an example of a function that returns the quadratic roots, given the coefficients. We assume that the roots are real. import math def quadroot(a, b, c): discr = (b * b) - (4 * a * c) discr_sqrt = math.sqrt(discr) root1 = (-b + discr_sqrt) / (2 * a) root2 = (-b - discr_sqrt) / (2 * a) return root1, root2 r1, r2 = quadroot(1, 3, -10) print r1, r2 In the example script above quadroot.py, we need the square root function which is not a built-in function in python (like C). We need to use a library to get that function. Libraries in python are called modules and using a module in our python program is done my simply importing the particular module. The line import math imports the module math. Once this line is executed, the functions defined in the math modules are available for use. Unlike C, the members (functions, variables, classes, etc.) of the math module are not imported into the same namespace as our main program, rather they are imported into the math namespace. Thus, in order to access any member of the math module, we need to prefix it with math.. For example the sqrt() function is called as math.sqrt(). This example also illustrates another feature of python. Python functions can return tuples. This means that multiple values can be returned and assigned to an equal number of variables. In this case, two values are returned. 5
6 After making the script file above executable with chmod, we can run it on the shell with the command line../quadroot The output will be If we run the program with the parameters to quadroot() to be 1, 3 and 10. We get the following output since the math.sqrt() function will not work for negative numbers. Traceback (most recent call last): File "./quadroot.py", line 12, in <module> r1, r2 = quadroot(7, 3, 10) File "./quadroot.py", line 7, in quadroot discr_sqrt = math.sqrt(discr) ValueError: math domain error We need to change our program so that it works for complex numbers too. We could do this my modifying our program to check for the value of the discriminant and calculate the complex solution accordingly. Python as we mentioned earlier has extensive standard library. It turns out that a complex version of the math module exists and is called cmath. All we need to do is to import cmath instead of math. But, now since the functions we need (including sqrt()) will be imported into the cmath namespace instead of the math namespace, we would have to change every occurence of math. in our program to cmath.. We can avoid this. Python supports renaming the namespace that the members of a module are imported into, the default being the same name as the module. Thus our new complex capable program is. import cmath as math def quadroot(a, b, c): discr = (b * b) - (4 * a * c) discr_sqrt = math.sqrt(discr) root1 = (-b + discr_sqrt) / (2 * a) root2 = (-b - discr_sqrt) / (2 * a) return root1, root2 r1, r2 = quadroot(1, 3, 10) print r1, r2 Only the import line has been changed. Now the cmath module which has complex versions of the same functions as the math module is imported. The members are imported into the math namespace by using the as keyword in the import line. And the output is. ( j) ( j) 6
7 6 help(), dir() and type() Within the python interpreter, we can get documentation about a built-in function or imported function using the help() built-in function. For example. help(len) Displays short documentation on the len() built-in function. Also import math help(math.sqrt) Will display short documentation on the sqrt() function defined in the math module. The dir() built-in function prints the members of a module or class. For example, in order to know what are the functions, classes and variables defined in the math module we can use. import math dir(math) [ doc, name, package, acos, acosh, asin, asinh, atan, atan2, atanh, ceil, copysign, cos, cosh, degrees, e, exp, fabs, factorial, floor, fmod, frexp, fsum, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, pi, pow, radians, sin, sinh, sqrt, tan, tanh, trunc ] From the output above, we know that some of the names in the dir() output are variables and others are functions. In order to know the type of a variable, the type() built-in function can be used. type(math.asin) <type builtin_function_or_method > type(math.pi) <type float > 7 Methods The datatypes that we described earlier are in fact objects. Although that might not make sense at this moment, it means that a variable of a particular datatype has some functions that operate on the value that it contains. These functions, called methods are bound to that variable. In order to know what are the methods available for particular variable we can use the dir() built-in function which will list them. The string datatype has several methods that operate on the string value. a = "hello, world" b = "another string" dir(a) [ add, class, contains, delattr, doc, eq, 7
8 format, ge, getattribute, getitem, getnewargs, getslice, gt, hash, init, le, len, lt, mod, mul, ne, new, reduce, reduce_ex, repr, rmod, rmul, setattr, sizeof, str, subclasshook, _formatter_field_name_split, _formatter_parser, capitalize, center, count, decode, encode, endswith, expandtabs, find, format, index, isalnum, isalpha, isdigit, islower, isspace, istitle, isupper, join, ljust, lower, lstrip, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill ] a.upper() HELLO, WORLD a.title() Hello, World a.replace("l","x") hexxo, worxd b.replace("the","yy") anoyyr string In a similar way the list datatype also supports several functions. mylist = ["orange", "apple", 23, (5,6)] mylist.append("endval") print mylist [ orange, apple, 23, (5, 6), endval ] mylist.remove("apple") print mylist [ orange, 23, (5, 6), endval ] mylist.insert(1, "mango") print mylist [ orange, mango, 23, (5, 6), endval ] print mylist.index(23) 2 print mylist.index((5,6)) 3 8 List comprehensions List comprehensions provide a concise way to write statements that produce a list. A list comprehension consists of an expression with a for statement within brackets. More for or if statments may follow the initial for. example, in order to generate a list of the first 10 powers of two using a for loop. powertwo = [] for i in range(10): 8
9 powertwo.append(2**i) print powertwo The same result can be obtained by using a list comprehension which is far more compact. powertwo = [2**i for i in range(10)] print powertwo Output will be [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] If we wanted to wanted get powers of two for odd exponents between 0 and 10. powertwo = [2**i for i in range(10) if i%2!= 0] print powertwo The Output being [2, 8, 32, 128, 512] 9 File Input/Output The open() built-in function is used to open a file for reading or writing. If the open() function succeeds, it return a file object which has several methods and behaves in certain ways when used in constructs. The examples will illustrate this. We use our earlier example text file comfilens.txt. C C C C B N B N B N A program to read each line and print lines that have C in the first column would look like. import sys ifile = open(sys.argv[1], r ) for line in ifile: 9
10 cols = line.split() if "C" in cols[0]: print line, ifile.close() In the example above, we first import the module sys which contains the list argv. The elements of sys.argv are the command line parameters, with sys.argv[0] being the command itself. The first parameter to the open() function is the name of the file to open, and the second parameter is the mode which is usually "r" for reading, "w" for writing and "rw" for both. The additional mode "b" has an effect on non- UNIX platforms like Windows. open() returns a file object which is bound to the name ifile. The file object supports iteration just like Lists and other sequence types. This means the object can be used in the for loop, where in each iteration, a line from the file is read, and the resulting string is assigned to the variable name line. The split() method of the string object returns a list in which each element is a word split by whitespace. Like other methods, split() can take parameters (see help(str.split)). mystring = "This is a sentence with some words" wrdlist = mystring.split() print wrdlist [ This, is, a, sentence, with, some, words ] The first element of the list cols which is cols[0] contains the first word of the input line. If the string C matches or is a substring of the string in col[0] then the line is printed. The trailing comma after the variable name in the print statement, suppresses the printing of a newline character. We do this because a newline character is already present at the end of the string value of variable line which will be printed. The close() method of the file object closes the file. The next example shows how the write() method of the file object is used. The import sys ofile = open(sys.argv[1], w ) num = int(sys.argv[2]) a, b = 0, 1 for i in range(num): ofile.write(str(a) + "\n") a, b = b, a+b ofile.close() Running the script with./fibwrite.py fibfile.txt 10 will write the first 10 fibonacci numbers to the file fibfile.txt. 10
11 10 Examples 10.1 cwords.py: Count Occurrences of a Word This python program does the same thing as the bash shell script we had written earlier with the same name. It counts the number of occurrences of a word in the text read from standard input (stdin). The word to count is specified as a command line argument. import sys count = 0 for line in sys.stdin: for word in line.lower().translate(none,,.()"\ ).split(): if word == sys.argv[1]: count += 1 print count The for loop will be familiar from earlier examples. Looking at the inner for loop, we chain together method calls. For example the line in the program for word in line.lower().translate(none,,.()"\ ).split() first, calling the lower() method on line returns the string in line with all characters converted to lowercase. The translate() method is called on that result (which is still a string). The translate() method of a string takes two arguments, the first is a translation table for mapping one set of characters to another set, and the second argument is the set of characters to delete from the string. Since we want to delete all punctuation marks from the string and do not need to do any translation. We give the null data type None as the first argument, and the set of characters to delete as the second. The split() method returns a list of words which have been split from line separated by whitespace. The above chained method call is equivalent to writing temp = line.lower() temp = temp.translate(none,,.()"\ ) temp = temp.split() for word in temp: Since each step above returns a string and we need to call a method of that string in the next step, chaining can be used to make the calls more compact. The condition for the if statement checks if word is equal to the string supplied as the command line argument, and increments the count variable if it is os.path, glob and re Modules The program below reads each file with the extension.txt from the directory source, removes duplicate lines and writes the output to a file with the same name but with the extension changed to.out in the directory dest. 11
12 import glob import os.path import re srcfiles = glob.glob(os.path.join( source, *.txt )) for filename in srcfiles: ifile = open(filename, r ) lines = ifile.readlines() lines = set(lines) ofilename = re.sub(.txt$,.out, filename) ofilename = re.sub( ^source, dest, filename) ofile = open(ofilename, w ) for line in lines: ofile.write(line) ifile.close() ofile.close() The import lines import the modules glob, os.path and re. The module glob includes functions for expanding shell glob expressions, os.path has functions for manipulation of pathnames and re is the regular expression module. The line srcfiles = glob.glob(os.path.join( source, *.txt )) stores the names of all the files in the directory source that end with the extension.txt into a list named srcfiles. The function os.path.join() joins each argument together using the appropriate pathname separator and returns it. On a Linux system, the command written in the interactive interpreter will give the output below. os.path.join( source, *.txt ) source/*.txt We use the join() function instead of inserting the / character because join() will use the appropriate character for the platform it is running on. Thus the line above will work even if the script is run on a system running Windows. The glob() function of the glob module expands the glob expression that is given as an argument and returns the list of pathnames that it matches. The for loop iterates over each of the filenames in srcfiles and opens the file and assigns the name ifile to the file object. The readlines() method of the file object returns a list in which each element is a line from the file. lines = set(lines) The list of lines is passed as an argument to the set() built-in function which creates a set datatype from the list. Since a set cannot contain duplicates, only unique lines will be present in the set. Note that the variable name lines now references a set rather than a list. The lines below utilise the sub() function of the re regular expression module. The sub() function performs the same function as the sed substitution 12
13 s command. It takes three arguments. The first is a regular expression. The second is the replacement string. And the third argument is the string on which the substitution is to be made. sub() will substitute all matches of the regular expression with the replacement string. ofilename = re.sub(.txt$,.out, filename) ofilename = re.sub( ^source, dest, filename) Here, the.txt extension is replaced with the.out extension and the directory source is replaced with dest in the pathname referenced by variable filename. The line ofile = open(ofilename, w ) opens the filename referenced by variable ofilename and assigns the file object to the variable name ofile. The loop for line in lines: ofile.write(line) iterates over each element in the set lines which contains the unique lines and associates it with the variable name line. line is written out to the file ofile using the write() method. Finally, before the loop iterates over the next file, ifile and ofile are closed with the close() method of the file object. ifile.close() ofile.close() 10.3 SciPy Package The SciPy package is an extensive scientific computing library for python. Among the many subpackages, it includes Discrete Fourier Transform algorithms, sparse and dense linear algebra, integration routines, signal and image processing tools. Documentation for each of the modules in the SciPy package is available using the python help() built-in function. For a list of packages in SciPy use help scipy after loading the SciPy module using import scipy. The SciPy packages is built upon and uses the NumPy library which implements fast multidimensional array types in python. The arrays are faster than native python lists and support array operations. For example the multiplication operator * between a NumPy array and a scalar return an array with each of the elements multiplied by the scalar. The same operation on a list will return a list with twice the length and its elements repeated. A package related to SciPy and NumPy is matplotlib. Matplotlib is a python library that provides 2D plotting capabilities. Matplotlib can produce publication quality images. It provides an interface to the user called pyplot which is in many respects similar to that provided by MATLAB R. The following example illustrates some of the capabilities for scientific computing that the combination of NumPy, SciPy and matplotlib can provide. The example creates a time series signal consisting of three summed sinusoids of different frequencies. The SciPy package fftpack is used to calculate the Discrete Fourier Transform of the signal. Matplotlib is used to plot the time series signal and its frequency domain representation. 13
14 import scipy as sp import matplotlib.pyplot as plt import scipy.fftpack as fft taxis = sp.linspace(0, 2*sp.pi, 16384) sig = sp.cos(100*taxis) + sp.cos(400*taxis) + sp.cos(1000*taxis) plt.subplot( 211 ) plt.plot(taxis, sig) SIG = fft.fft(sig) SIG = fft.fftshift(sig) SIG = abs(sig) faxis = sp.arange(-8192, 8192, 1) plt.subplot( 212 ) plt.plot(faxis, SIG) plt.xlim(-1200, 1200) plt.show() We take a closer look at the lines in the program. The lines import scipy as sp import matplotlib.pyplot as plt import scipy.fftpack as fft each import the modules scipy, matplotlib.pyplot and scipy.fftpack. Instead of using the default namespace to load the modules into, which is the same name as the module, we specify shorter names for convenience. The scipy module is loaded into the namespace sp. Module matplotlib.pyplot is loaded into namespace plt. And scipy.fftpack is loaded into namespace fft. We can now use the namespace names that we have chosen to access members of each of the modules. The line taxis = sp.linspace(0, 2*sp.pi, 16384) uses the NumPy (which is included in the SciPy module) function linspace(). linspace() returns a sequence of numbers between an interval. It takes three arguments. The first is the start of the sequence, the second is the end, and the third argument is the number of entries in the sequence. linspace() returns a NumPy array. The pi member of the scipy module is a constant with the value of π. The line above will generate an array of numbers beginning from 0 and ending with 2π. The result of the statement above can be seen in the interactive interpreter. taxis = sp.linspace(0, 2*sp.pi, 16384) print taxis [ e e e-04, e e e+00] 14
15 Next, we look at the line. sig = sp.cos(100*taxis) + sp.cos(400*taxis) + sp.cos(1000*taxis) In this line we use the cos() function defined in the SciPy module. The math module also provides the cos() function but we cannot use it here. Notice that the argument to the cos() function is an array which is multiplied by a scalar. Thus we are passing an array as the argument to cos(). The cos() function in the math module only supports scalar arguments. The cos() function in the SciPy module accepts array arguments. In this case it applies the cos() function to each element of the array and returns the resulting array. Thus the line above creates an array which is the sum of three discrete sinusoids and associates the name sig with it. The next two lines are matplotlib functions. The pyplot interface design is such that when each pyplot function is called, a change is made to the current figure. That is, pyplot is stateful and remembers the change that each pyplot function make. Once the current figure is in the state that is desired, it can be finally displayed. plt.subplot( 211 ) plt.plot(taxis, sig) The subplot(211) function tells matplotlib to create two plots arranged as 2 rows and 1 column and to select the first among them as the current plot. If we wanted 6 plots arranged as 3 rows and 2 columns and the 4th one as the current plot, we would use subplot(324). All subsequent pyplot functions affect the current plot. In our case the next line creates a line plot consisting of x-axis values in array taxis and the corresponding y-axis values in array sig. The next line uses the fft function defined in the scipy.fftpack module. SIG = fft.fft(sig) fft.fft(sig) returns the Discrete Fourier Transform of the array sig. The result is an array of complex numbers. The array returned by the fft() function is in frequency space. In the example, SIG[0] will contain the zero-frequency term. SIG[1] to SIG[8191] will contain the positive frequency terms and SIG[8192] to SIG[16383] will have negative frequency terms. We would like the frequency domain array to be centred at the zero frequency term with negative terms on the left and positive terms on the right. The fftshift() function returns the centred frequency domain array. SIG = fft.fftshift(sig) The next line SIG = abs(sig) converts each of the complex values in SIG to its absolute value or magnitude. We need to generate the values of the x-axis so that they match the centred time domain array. We do this with the line. faxis = sp.arange(-8192, 8192, 1) 15
16 The arange() function returns an array whose first value is and last value is 8191 with the difference of 1 between consecutive values. This corresponds with the frequencies of the coefficients in the frequency domain array SIG. The next lines are similar to what we have seen earlier. The subplot() function sets the second plot as the current plot. The plot() function generates a line plot with the frequencies contained in faxis as the x-axis and the corresponding coefficients contained in SIG as the y-axis. The function call xlim(-1200, 1200 tells matplotlib to limit the displayed range of the x-axis for subplot 2 to the values between and 1200, which is the frequency range we are interested in. plt.subplot( 212 ) plt.plot(faxis, SIG) plt.xlim(-1200, 1200) Finally the pyplot function plt.show() displays the all the plots on the output device, which is the screen in our case. 16
(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.
Basics of Python by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 13 February 2014 11:59 AM Topics to be Covered (Not in any specific order.) Basic I/O in
More informationPython Tutorial. Day 1
Python Tutorial Day 1 1 Why Python high level language interpreted and interactive real data structures (structures, objects) object oriented all the way down rich library support 2 The First Program #!/usr/bin/env
More information(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 16 October :50 PM
Basics of Python by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 16 October 2014 03:50 PM Topics to be Covered (Not in any specific order.) Basic I/O in Python
More informationBuilt-in Types of Data
Built-in Types of Data Types A data type is set of values and a set of operations defined on those values Python supports several built-in data types: int (for integers), float (for floating-point numbers),
More informationIntroductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University
Introductory Linux Course Martin Dahlö UPPMAX Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University August, 2018 Outline Python basics get started with Python Data types Control
More informationIntroductory Linux Course. Python I. Pavlin Mitev UPPMAX. Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University
Introductory Linux Course Python I Pavlin Mitev UPPMAX Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University August, 2017 Outline Python introduction Python basics get started with
More informationIPSL python tutorial: some exercises for beginners
1 of 9 10/22/2013 03:55 PM IPSL python tutorial: some exercises for beginners WARNING! WARNING! This is the FULL version of the tutorial (including the solutions) WARNING! Jean-Yves Peterschmitt - LSCE
More informationIntroductory Linux Course. Python I. Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University
Introductory Linux Course Python I Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University nina.fischer@icm.uu.se January 12, 2017 Outline q Python introducjon q Python basics get started
More informationIntroductory Linux Course. Python I. Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University
Introductory Linux Course Python I Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University nina.fischer@icm.uu.se August 26, 2016 Outline q Python introducjon q Python basics get started
More informationPython. Olmo Zavala R. Python Exercises. Center of Atmospheric Sciences, UNAM. August 24, 2016
Exercises Center of Atmospheric Sciences, UNAM August 24, 2016 NAND Make function that computes the NAND. It should receive two booleans and return one more boolean. logical operators A and B, A or B,
More informationProgramming for Engineers in Python. Recitation 2
Programming for Engineers in Python Recitation 2 Plan Range For loop While loop Lists Modules Operations Arithmetic Operations: + plus - minus * multiply / divide (int / float) % modulo (remainder) **
More informationHigh Level Scripting. Gino Tosti University & INFN Perugia. 06/09/2010 SciNeGhe Data Analysis Tutorial
High Level Scripting Part I Gino Tosti University & INFN Perugia What is a script? Scripting Languages It is a small program able to automate a repetitive and boring job; It is a list of commands that
More informationIntroduction to Python for Plone developers
Plone Conference, October 15, 2003 Introduction to Python for Plone developers Jim Roepcke Tyrell Software Corporation What we will learn Python language basics Where you can use Python in Plone Examples
More informationPython - 2. Jim Eng
Python - 2 Jim Eng jimeng@umich.edu Lists Dictionaries Try... except Methods and Functions Classes and Objects Midterm Review Overview Patterns in programming - 1 Sequential steps Conditional steps Repeated
More informationPython Objects. Charles Severance. Python for Everybody
Python Objects Charles Severance Python for Everybody www.py4e.com Warning This lecture is very much about definitions and mechanics for objects This lecture is a lot more about how it works and less about
More informationSequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python
Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted
More informationChap 6 Function Define a function, which can reuse a piece of code, just with a few different values.
Chap 6 Function Define a function, which can reuse a piece of code, just with a few different values. def tax(bill): """Adds 8% tax to a restaurant bill.""" bill *= 1.08 print "With tax: %f" % bill return
More informationEssentials for Scientific Computing: Bash Shell Scripting Day 3
Essentials for Scientific Computing: Bash Shell Scripting Day 3 Ershaad Ahamed TUE-CMS, JNCASR May 2012 1 Introduction In the previous sessions, you have been using basic commands in the shell. The bash
More informationSI Networked Computing: Storage, Communication, and Processing, Winter 2009
University of Michigan Deep Blue deepblue.lib.umich.edu 2009-01 SI 502 - Networked Computing: Storage, Communication, and Processing, Winter 2009 Severance, Charles Severance, C. (2008, December 19). Networked
More informationProgramming for Engineers in Python. Recitation 3
Programming for Engineers in Python Recitation 3 Plan Modules / Packages Tuples Mutable / Imutable Dictionaries Functions: Scope Call by Ref / Call by Val Frequency Counter Python Code Hierarchy Statement
More informationLab 7: Reading Files, Importing, Bigram Function. Ling 1330/2330: Computational Linguistics Na-Rae Han
Lab 7: Reading Files, Importing, Bigram Function Ling 1330/2330: Computational Linguistics Na-Rae Han Objectives Importing Reading text files range() Bigram function More sorting with sorted() sorted()
More informationStrings. Looping. dna = 'ATGTAGC' print(dna) In [1]: ATGTAGC. You can loop over the characters of a string using a for loop, as we saw on Tuesday:
Strings A string is simply a sequence of characters. From a biological perspective, this is quite useful, as a DNA sequence is simply a string composed of only 4 letters, and thus easily manipulated in
More informationProgramming for Engineers in Python. Recitation 3 Functions
Programming for Engineers in Python Recitation 3 Functions Plan Short review FOR and Lists Python references Mutable vs. immutable data types List references Functions Scope Call by assignment Global variables
More informationComputer Science 121. Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans
Computer Science 121 Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans 3.1 The Organization of Computer Memory Computers store information as bits : sequences of zeros and
More informationSECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING
SECOND EDITION SECOND EDITION Covers Python 3 SAMPLE CHAPTER First edition by Daryl K. Harms Kenneth M. McDonald Naomi R. Ceder MANNING The Quick Python Book Second Edition by Naomi R. Ceder Chapter 4
More informationProgramming environments. Introduction to Python. Adrian Copie, Ph.D.
Programming environments Introduction to Python Adrian Copie, Ph.D.! email: adrian.copie@info.uvt.ro, adrian.copie@e-uvt.ro UVT: room 050B 1 2 Bibliography 3 Mark Lutz - Learning Python (O Reilly) Leaning
More informationEssentials for Scientific Computing: Stream editing with sed and awk
Essentials for Scientific Computing: Stream editing with sed and awk Ershaad Ahamed TUE-CMS, JNCASR May 2012 1 Stream Editing sed and awk are stream processing commands. What this means is that they are
More informationBabu Madhav Institute of Information Technology, UTU 2015
Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?
More informationStrings. Chapter 6. Python for Everybody
Strings Chapter 6 Python for Everybody www.py4e.com String Data Type A string is a sequence of characters A string literal uses quotes 'Hello' or "Hello" For strings, + means concatenate When a string
More informationPrinceton University COS 333: Advanced Programming Techniques A Subset of Python 2.7
Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7 Program Structure # Print "hello world" to stdout. print 'hello, world' # Print "hello world" to stdout. def f(): print
More informationAdvanced Python. Executive Summary, Session 1
Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.
More informationA. Matrix-wise and element-wise operations
USC GSBME MATLAB CLASS Reviewing previous session Second session A. Matrix-wise and element-wise operations A.1. Matrix-wise operations So far we learned how to define variables and how to extract data
More informationHandling Strings and Bytes
Chapter 9 Handling Strings and Bytes In this chapter, we present some of the most used methods in strings and bytes objects. Strings are extremely useful to manage most of the output generated from programs,
More informationPart IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,
Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith ("
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationPython. Executive Summary
Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"
More informationARTIFICIAL INTELLIGENCE AND PYTHON
ARTIFICIAL INTELLIGENCE AND PYTHON DAY 1 STANLEY LIANG, LASSONDE SCHOOL OF ENGINEERING, YORK UNIVERSITY WHAT IS PYTHON An interpreted high-level programming language for general-purpose programming. Python
More information(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.
Basics of Python - 2 by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 54 Sunday 16 February 2014 05:30 PM Our First Program - Rewritten! Let us introduce the following
More informationDownloaded from Chapter 2. Functions
Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create
More informationAssignment 1: Getting Started with Python
Assignment 1: Getting Started with Python This tutorial will cover the basics of working in the Unix environment for the USC aludra.usc.edu machines and a small Python tutorial. It assumes you already
More informationLecture 6: A step back
Lecture 6: A step back Last time We introduced a scripting language known as Python -- We started with the barest of motivation in terms of historical context and then jumped right in, focusing mainly
More informationPython Programming. Lecture 1. January 25 th. University of Pennsylvania 2010, Adam Aviv CIS 192 Spring
Python Programming Lecture 1 January 25 th 2010, Adam Aviv CIS 192 Spring 2010 1 Welcome Where are you? Levine 100, Wu & Chen Auditorium 2/8 we will be in Heilmeir Hall (Towne 100) Who am I? Adam Aviv,
More informationDuration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT
Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT Online Classes are also available Recorded class will be given if you miss any day interview tips and quiz at end of every module
More informationStandard Library. Built-in Functions
2 The Standard Library Lab Objective: Python is designed to make it easy to implement complex tasks with little code. To that end, every Python distribution includes several built-in functions for accomplishing
More informationCOMP 364: Classes, Objects, and Names
COMP 364: Classes, Objects, and Names Carlos G. Oliver, Christopher Cameron September 13, 2017 1/26 Outline 1. 202 vs 364 2. Development Environment Recap 3. Basic Data Types 4. Variables 2/26 Your Development
More informationStrings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break
Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Strings Upsorn Praphamontripong CS 1111 Introduction to Programming Spring 2018 Strings Sequence of characters
More information2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1
2.1 Indefinite Loops The final kind of control flow is Python s indefinite loop, the while loop. It functions much like the for loop in that it repeatedly executes some body of statements. The difference
More informationString Processing CS 1111 Introduction to Programming Fall 2018
String Processing CS 1111 Introduction to Programming Fall 2018 [The Coder s Apprentice, 10] 1 Collections Ordered, Dup allow List Range String Tuple Unordered, No Dup Dict collection[index] Access an
More informationIntroduction to Text-Processing. Jim Notwell 23 January 2013
Introduction to Text-Processing Jim Notwell 23 January 2013 1 Stanford UNIX Resources Host: cardinal.stanford.edu To connect from UNIX / Linux / Mac: ssh user@cardinal.stanford.edu To connect from Windows
More informationWorking with Sequences: Section 8.1 and 8.2. Bonita Sharif
Chapter 8 Working with Sequences: Strings and Lists Section 8.1 and 8.2 Bonita Sharif 1 Sequences A sequence is an object that consists of multiple data items These items are stored consecutively Examples
More informationCOLLEGE OF ENGINEERING, NASHIK-4
Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING Important PYTHON Questions 1. What is Python? Python is a high-level, interpreted, interactive and object-oriented
More informationBash scripting basics
Bash scripting basics prepared by Anatoliy Antonov for ESSReS community September 2012 1 Outline Definitions Foundations Flow control References and exercises 2 Definitions 3 Definitions Script - [small]
More information9.2 Linux Essentials Exam Objectives
9.2 Linux Essentials Exam Objectives This chapter will cover the topics for the following Linux Essentials exam objectives: Topic 3: The Power of the Command Line (weight: 10) 3.3: Turning Commands into
More informationPart VI. Scientific Computing in Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,
Part VI Scientific Computing in Python Compact Course @ Max-Planck, February 16-26, 2015 81 More on Maths Module math Constants pi and e Functions that operate on int and float All return values float
More information5 File I/O, Plotting with Matplotlib
5 File I/O, Plotting with Matplotlib Bálint Aradi Course: Scientific Programming / Wissenchaftliches Programmieren (Python) Installing some SciPy stack components We will need several Scipy components
More informationHow to Design Programs Languages
How to Design Programs Languages Version 4.1 August 12, 2008 The languages documented in this manual are provided by DrScheme to be used with the How to Design Programs book. 1 Contents 1 Beginning Student
More informationIntroduction to Scientific Computing with Python, part two.
Introduction to Scientific Computing with Python, part two. M. Emmett Department of Mathematics University of North Carolina at Chapel Hill June 20 2012 The Zen of Python zen of python... fire up python
More informationCourse May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points
May 18, 2017 3 I/O 3 I/O 3 I/O 3 ASC, room A 238, phone 089-21804210, email hartmut.ruhl@lmu.de Patrick Böhl, ASC, room A205, phone 089-21804640, email patrick.boehl@physik.uni-muenchen.de. I/O Scientific
More informationDM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.
DM536 / DM550 Part 1 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/! CALLING FUNCTIONS 2 Calling Functions so far we have seen three different
More informationGIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes
GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and
More informationPart VI. Scientific Computing in Python. Alfredo Parra : Scripting with Python Compact Max-PlanckMarch 6-10,
Part VI Scientific Computing in Python Compact Course @ Max-PlanckMarch 6-10, 2017 63 Doing maths in Python Standard sequence types (list, tuple,... ) Can be used as arrays Can contain different types
More informationList of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12
List of squares Program to generate a list containing squares of n integers starting from 0 Example list n = 12 squares = [] for i in range(n): squares.append(i**2) print(squares) $ python3 squares.py
More informationENGR (Socolofsky) Week 07 Python scripts
ENGR 102-213 (Socolofsky) Week 07 Python scripts A couple programming examples for this week are embedded in the lecture notes for Week 7. We repeat these here as brief examples of typical array-like operations
More informationBasic Linux (Bash) Commands
Basic Linux (Bash) Commands Hint: Run commands in the emacs shell (emacs -nw, then M-x shell) instead of the terminal. It eases searching for and revising commands and navigating and copying-and-pasting
More informationArithmetic and Logic Blocks
Arithmetic and Logic Blocks The Addition Block The block performs addition and subtractions on its inputs. This block can add or subtract scalar, vector, or matrix inputs. We can specify the operation
More information18.1. CS 102 Unit 18. Python. Mark Redekopp
18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two
More informationUNIT-III. All expressions involving relational and logical operators will evaluate to either true or false
UNIT-III BOOLEAN VALUES AND OPERATORS: A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces if they are
More informationIntroduction to Programming and 4Algorithms Abstract Types. Uwe R. Zimmer - The Australian National University
Introduction to Programming and 4Algorithms 2015 Uwe R. Zimmer - The Australian National University [ Thompson2011 ] Thompson, Simon Haskell - The craft of functional programming Addison Wesley, third
More informationCSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.
CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:
More informationPython Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]
Python Lists: Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). All the items belonging to a list can be of different data type.
More informationWorksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords
Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long
More informationStatistical Data Analysis: Python Tutorial
1 October 4, 2017 Statistical Data Analysis: Python Tutorial Dr A. J. Bevan, Contents 1 Getting started 1 2 Basic calculations 2 3 More advanced calculations 4 4 Data sets 5 4.1 CSV file input.............................................
More informationLISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University
LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python
More informationCS Programming Languages: Python
CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer
More informationStrings are actually 'objects' Strings
Strings are actually 'objects' Strings What is an object?! An object is a concept that we can encapsulate data along with the functions that might need to access or manipulate that data. What is an object?!
More informationMacro Programming Reference Guide. Copyright 2005 Scott Martinez
Macro Programming Reference Guide Copyright 2005 Scott Martinez Section 1. Section 2. Section 3. Section 4. Section 5. Section 6. Section 7. What is macro programming What are Variables What are Expressions
More informationIntroduction to Python
Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1 Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code
More informationDM550/DM857 Introduction to Programming. Peter Schneider-Kamp
DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ Operator Precedence expressions are evaluated left-to-right
More informationChapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018
Chapter 8: More About Strings COSC 1436, Summer 2018 Dr. Zhang 7/10/2018 Creating Strings The str Class s1 = str() # Create an empty string s2 = str("welcome") # Create a string Welcome Python provides
More informationSymbols. Anscombe s quartet, antiderivative, 200. bar charts for exercise, for expenses, Barnsley fern, drawing,
Index Symbols + (addition operator), 2 {} (curly brackets), to define a set, 122 δ (delta), 184 / (division operator), 2 ε (epsilon), 192, 197 199 == (equality operator), 124 e (Euler s number), 179 **
More informationProgramming with Python
Programming with Python EOAS Software Carpentry Workshop September 21st, 2016 https://xkcd.com/353 Getting started For our Python introduction we re going to pretend to be a researcher studying inflammation
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationLab copy. Do not remove! Mathematics 152 Spring 1999 Notes on the course calculator. 1. The calculator VC. The web page
Mathematics 152 Spring 1999 Notes on the course calculator 1. The calculator VC The web page http://gamba.math.ubc.ca/coursedoc/math152/docs/ca.html contains a generic version of the calculator VC and
More informationpython 01 September 16, 2016
python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7
More informationGetting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013
CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?
More informationAN INTRODUCTION TO MATLAB
AN INTRODUCTION TO MATLAB 1 Introduction MATLAB is a powerful mathematical tool used for a number of engineering applications such as communication engineering, digital signal processing, control engineering,
More informationERTH3021 Exploration and Mining Geophysics
ERTH3021 Exploration and Mining Geophysics Practical 1: Introduction to Scientific Programming using Python Purposes To introduce simple programming skills using the popular Python language. To provide
More informationBourne Shell Reference
> Linux Reviews > Beginners: Learn Linux > Bourne Shell Reference Bourne Shell Reference found at Br. David Carlson, O.S.B. pages, cis.stvincent.edu/carlsond/cs330/unix/bshellref - Converted to txt2tags
More informationSAMPLE CHAPTER. Naomi Ceder MANNING. Foreword by Nicholas Tollervey
SAMPLE CHAPTER Naomi Ceder Foreword by Nicholas Tollervey MANNING The Quick Python Book Third Edition by Naomi Ceder Sample Chapter 4 Copyright 2018 Manning Publications brief contents PART 1 STARTING
More informationChapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52
Chapter 2 Python Programming for Physicists Soon-Hyung Yook March 31, 2017 Soon-Hyung Yook Chapter 2 March 31, 2017 1 / 52 Table of Contents I 1 Getting Started 2 Basic Programming Variables and Assignments
More informationFinding, Starting and Using Matlab
Variables and Arrays Finding, Starting and Using Matlab CSC March 6 &, 9 Array: A collection of data values organized into rows and columns, and known by a single name. arr(,) Row Row Row Row 4 Col Col
More information06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python
CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison
More informationScript started on Thu 25 Aug :00:40 PM CDT
Script started on Thu 25 Aug 2016 02:00:40 PM CDT < M A T L A B (R) > Copyright 1984-2014 The MathWorks, Inc. R2014a (8.3.0.532) 64-bit (glnxa64) February 11, 2014 To get started, type one of these: helpwin,
More informationPathologically Eclectic Rubbish Lister
Pathologically Eclectic Rubbish Lister 1 Perl Design Philosophy Author: Reuben Francis Cornel perl is an acronym for Practical Extraction and Report Language. But I guess the title is a rough translation
More informationEE 355 Unit 17. Python. Mark Redekopp
1 EE 355 Unit 17 Python Mark Redekopp 2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 3 Python in Context Interpreted,
More informationExercise sheet 1 To be corrected in tutorials in the week from 23/10/2017 to 27/10/2017
Einführung in die Programmierung für Physiker WS 207/208 Marc Wagner Francesca Cuteri: cuteri@th.physik.uni-frankfurt.de Alessandro Sciarra: sciarra@th.physik.uni-frankfurt.de Exercise sheet To be corrected
More informationVariable and Data Type 2
The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 3 Variable and Data Type 2 Eng. Ibraheem Lubbad March 2, 2017 Python Lists: Lists
More informationCS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012
CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012 COMPUTER SCIENCE IN THE NEWS http://www.iospress.nl/ios_news/music to my eyes device converting
More informationENGR 102 Engineering Lab I - Computation
ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;
More informationIntroduction to Python Part 2
Introduction to Python Part 2 v0.2 Brian Gregor Research Computing Services Information Services & Technology Tutorial Outline Part 2 Functions Tuples and dictionaries Modules numpy and matplotlib modules
More information