Python Fundamentals

Scripting Languages

References
‡ http://www.linuxjournal.com/article/3882 ³Why Python?´ by Eric Raymond in the Linux Journal, May 1st 2000. http://www.tcl.tk/doc/scripting.html ³Scripting: Higher Level Programming for the 21st Century´, John K. Ousterhout, IEEE Computer, March 1998. http://www.geeksaresexy.net/2008/07/25/the-ascent-of-scriptinglanguages/ ³The ascent of scripting languages´ by Chip. July 25, 2008. From the site Geeks are Sexy Œ Python tutorial: Python web page: http://www.python.org/

‡

‡

‡ ‡

What is a Scripting Language?
‡ Wikipedia: A scripting language, script language or extension language, is a programming language that controls a software application. "Scripts" are often treated as distinct from ³programs", which execute independently from any other application.

and combine them so they work together. maybe in different languages. scripting languages take pre-existing components. of a UNIX system ‡ When used like this. .Early Scripting Languages ‡ Controlled the actions of system programs ‡ Job Control Language (JCL):controlled batch job executions on IBM mainframes ‡ Shell scripts: A series of instructions to the shell. or command line interpreter.

Example Shell Script from Ousterhout ‡ select | grep scripting | wc where ± select is a program to read and output the text that is currently selected on the display ± grep is a program reads input and outputs the lines containing "scripting". ± wc is a program to count the lines in its input. ± ³|´ is the pipe command that directs the output from one program to the input of the next program. .

for example . Python.Modern Scripting Languages ‡ Perl. « ‡ More like a traditional programming language than early scripting languages. ‡ Higher level in the sense that programmers don¶t have to worry about many of the details that are a part of C-like languages ± No explicit memory allocation/deallocation. Ruby.

Modern Scripting Languages ‡ It¶s possible to write full-featured programs in these languages ‡ Used frequently today for ³quick-and-dirty´ programming ± ± Quick results ± Small programs ‡ See next definition .

com/EBchecked/topic/1086439/sc ripting-language>. They are intended to solve relatively small programming problems that do not require the overhead of data declarations and other features needed to make large programs manageable. Encyclopædia Britannica Online. for specialpurpose file-manipulation programs.What is a Scripting Language? ‡ "scripting language.britannica. because they are easy to learn. 2008." Encyclopædia Britannica. 2008 <http://www. ‡ ³Scripting languages are sometimes called little languages. 30 Sep.´ . Scripting languages are used for writing operating system utilities. and.

± Reason: no extra compile time ‡ In the scripting language-as-glue-language mode. performance is dominated by the modules being connected by the scripting commands .Scripts are Usually Interpreted ‡ Using an interpreter instead of a compiler makes sense when programs change frequently and/or are very interactive.

OO as an afterthought.Why Python? ‡ No universal agreement on which scripting language is best ‡ Perl. others also have advocates ‡ Perl: good for system administration duties. Ruby. traditional scripting ± Awkward syntax. less readable than other languages ‡ Python ± has attracted many former Perl users .

automatic memory management. modular. easy to learn .Intro ‡ Python is a general purpose language that implements the imperative. ‡ Dynamic typing. and functional paradigms. ± Extensions can be written in C and C++ ± Other language versions (Jython.Python . large standard library.Net languages) ‡ Design philosophy: easy to read. exceptions. IronPython) support extensions written in Java and . object-oriented.

± Most features are the same or similar. but a few will cause older programs to break.1.1 ‡ Both versions are stable and suitable for use ‡ Python 2: compatible with more existing software ‡ Python 3: a major redesign ± Not backward compatible.Versions ‡ Production versions are 2.4 and 3.6. .1). ± Part of the Python philosophy ± don¶t clutter up the language with outdated features ‡ Write your programs to run in the CS lab (v 3.

Interesting Features ‡ White space does indicate meaning ± Instead of curly brackets or begin-end pairs. whitespace is used for block delimiters. ‡ ‡ ‡ ‡ No variable declarations Dynamic typing Associative arrays (dictionaries) Lists and slices .

Python will evaluate it: >>> a = 5 >>> b = 10 >>> a+b 15 Dynamic change of type >>> a = 'horse¶ >>> a = µ cart¶ >>> a + b µhorse cart¶ .Execution Modes Calculator mode: type in an expression.

³is´. -1) fact = fact * factor print ³the factorial of´. 1.Execution Modes .py # compute the factorial of a number def main( ): n = input(³enter a whole number´) fact = 1 for factor in range (n.Program #factorial. n.fact main( ) .

digits.Program Elements ‡ Identifiers: ± Must begin with letter or underscore. followed by any number of letters. underscores ‡ Variables: ± Do not need to be declared ± A variable is created when a value is assigned to it: Examples: num = 3 ± Can¶t be used in an expression unless it has a value ± Error message: Name Error ± means no value is associated with this name .

± This makes it possible to assign different object types to the same variable .Variables ‡ Variable names don¶t have types ± values (or objects) do ± A variable name has the type of the value it currently references ‡ Variables actually contain references to values (similar to pointers).

5 7.Variables contain references to data values A 3.0 cat Python handles memory management automatically. it will also execute garbage collection algorithms to reclaim any inaccessible memory locations. It will create new objects and store them in memory. if A = 10 and B = A.5 A=A* 2 A = ³cat´ A 3. A = A + 1 does not change the value of B . Python does not implement reference semantics.

/.Expressions ‡ An expression calculates a value ‡ Arithmetic operators: +. -. divide work just as they do in other C-style languages ‡ Spaces in an expression are not significant ‡ Parentheses override normal precedence . subtract. multiply. *. ** (exponentiation) ‡ Add.

# no new line ‡ Output items are automatically separated by a single space.} where the final comma in the list is optional ‡ Examples: print # prints a blank line print 3. y.Output Statements ‡ Statement syntax: (EBNF notation) print {expression. z + 10 # go to new line print ³the result is´ z. .

y = y. var} = expr{. y = 4. expr) >>> x. ‡ Multiple_assign var{. x >>> x 7 >>> y 4 >>> .Assignment Statements ‡ Syntax: Assignment variable = expression ‡ A variable¶s data type is determined by the type of the value assigned to it. 7 >>> x 4 >>> y 7 >>> x.

>>> y = input("enter a name ") enter a name "max" >>> y 'max' >>> number = input("Enter an integer ") Enter an integer 32 >>> number 32 >>> thing = input("enter an expression ") enter an expression 3 * 8 / 4 >>> thing 6 .Input ‡ Syntax: input variable = input(string) The string is used as a prompt.

Input ‡ The input statement can be part of a multiple assignment statement: >>> x. y = input("enter two comma-separated values: ") enter two comma-separated values: 13. 26 >>> x 13 >>> y 26 .

Input ‡ The raw_input function is another way to read string data ± No need to quote the input strings >>> s = raw_input("Enter a sentence ") Enter a sentence Python is easy! >>> s 'Python is easy!' >>> .

. Python will throw an exception. if user enters something inappropriate. if necessary r = float(raw_input(³enter radius´)) ‡ Now.Raw_input versus input ‡ raw_input reads everything as a string ‡ Using raw_input is a safety measure for reading data ± use a cast to get correct type.

Python Control Structures ‡ Python loop types: ± while ± for ‡ Decision statements: ± if ‡ Related features: ± range( ) ± break ± continue # a function # statements similar to # those in C/C++ .

‡ All other statements must be indented by the same amount ‡ To terminate a loop body. enter a blank line.General Information ‡ The first statement in the body of a loop must be indented. .

While Loop >>> x = 0 >>> while (x < 10): #remember semicolon! print x. non-zero is true The conditional operators are also the same Note indentation ± provided by the IDLE GUI . #prints on one line x = x + 1 0 1 2 3 4 5 6 7 8 9 Conditions are evaluated just as in C/C++: 0 is false.

n-1 ± range(start. n): begins at start instead of 0 ± range(start. n.For Loops ‡ Syntax: for <var> in <sequence>: <body> ‡ <sequence> can be a list of values or it can be defined by the range( ) function ± range(n) produces a list of values: 0. «. 1. step): uses step as the increment .

2): print i 6 8 10 .12. 0 1 2 >>> for i in range(5.>>> for i in range(3): print i. 5 6 7 8 9 >>> for i in range(6.10): print i.

0 1 2 3 4 5 6 7 8 9 10 11 12 .Ranges can also be specified using expressions: >>> n = 5 >>> for i in range(2*n +3): print i.

Using a List in a for loop Lists are enclosed in square brackets >>> for i in [3. 'elephant']: print i. 1]: print i. 2. cat dog elephant . 3 2 1 >>> for i in ['cat'. 'dog'.

. ‡ Each part must be followed with a semicolon and whitespace is used as the delimiters.If Statement ‡ Python if statement has three versions: ± The if (only one option) ± The if-else (two options) ± The if-elif-else (three or more options) ‡ The if-elif-else substitutes for the switch statement in other languages.

If-elif-else Statement x = input("enter an integer: ³) if x < 0: print µNegative¶ elif x == 0: print 'Zero' elif x == 1: print 'Single' else: print 'More' .

Strings ‡ String literals consist of characters enclosed in quotation marks (single or double) ‡ Use raw_input instead of input ‡ Individual characters are referenced by their index (indexes start at 0) ‡ Negative indexes work from right to left: >>> myName = "Joe Smith³ >>> myName[-3] 'i' .

String Operations ‡ Slicing: selects a µslice¶ or segment of a string <string>[<start>:<end>] >>> myName[2:7] 'e Smiµ ‡ If either <start> or <end> is omitted. the start and end of the string are assumed >>> myName[:5] 'Joe S' >>> myName[4:] 'Smith' >>> myName[:] 'Joe Smith' .

String Operations Concatenation (+) >>> "happy" + "birthday" 'happybirthday' >>> 'happy' + ' birthday' 'happy birthday¶ Repetition (*) >>> word = 'ha' >>> 3 * word 'hahaha' >>> word + 3 * '!' 'ha!!!' .

String Operations Other examples: >>> len(word) # length function 2 >>> len("ham and eggs") 12 >>> for ch in myName: print ch. J o e S m i t h .

concatenated. and repeated. ‡ The len() function will return the number of elements in the list .Lists ‡ A list is a comma-separated sequence of items. lists can be sliced. enclosed in square brackets ‡ Lists can be heterogeneous ± items don¶t have to be from the same data type ‡ Like strings. indexed.

>>> myList = ['milk'. 5.'eggs'. 'bread'] >>> x. 5. '018'] . 9 >>> yourList = [x.10] >>> myList[0:3] ['milk'. 'eggs'] >>> len(myList) 4 >>> yourList[:8] #try to exceed length [3. z. y. z = 3. 'eggs'. y. 5] >>> 2 * myList[1:2] ['eggs'. "018"] >>> yourList[0:2] [3.'bread'. 9.

Lists ‡ Unlike strings. 'butter'. and even change the length of the list . using the index >>> myList[1] = 'butter' >>> myList ['milk'. 100] ‡ You can also assign to slices. 'bread'. lists are mutable (can be changed) ± Make an assignment.

14. 32. 'sue'. 14. 44] #delete an element >>> data[3:4] = [] >>> data ['bob'. 14] >>> data ['bob'. 19. 44] #insert an element >>> data[1:1] = [19] >>> data ['bob'.List Slice Operations #create a list >>> data = ['bob'. 44] >>> data ['bob'. 44] . 32. 'dave'. 19. 'dave'. 44] #assign to a list slice >>> data[1:3] = ['dave'. 'sue'. 'dave'.

Sequences ‡ Strings and lists are both sequences. ‡ Sequence operations include <seq>+<seq> <seq> * (int-exp> <seq>[ ] <seq>[ : ] len(<seq>) for <var> in <seq> concatenation repetition indexing slicing length iteration .

'jack'.grades] >>> stRec ['A000'.'jack'. 97. 85]] >>> len(stRec) 3 . 97. 85] >>> stRec = ['A000'.Nested Lists >>> grades = [100. [100.

x) ± etc.1 in the Python tutorial to get a whole set of list functions: ± append(x) ± insert(i.More About Lists ‡ See Section 5. ‡ Since lists are objects. dot notation is used to call the functions .

85]] >>> stRec. 97. 'jack'] . 97. 'jack'. 85] >>> stRec ['A000'. [100. 97. 85]) >>> stRec ['A000'. 'jack'] >>> stRec.remove(grades) >>> stRec ['A000'.More Examples >>> stRec.pop(2) [100.append([100.

‡ See Section 5. strings) which are indexed sequentially.5 in the tutorial for more examples . dictionaries are an unordered collection of key-value pairs.Dictionaries ‡ Also called associative arrays ‡ Resemble hash tables ‡ Unlike sequences (lists. ‡ Items are retrieved according to their keys.

>>> roll = {1023: 'max', 0404: 'sue'} >>> roll[1023] 'max' >>> roll[9450] = 'alice' >>> roll {9450:'alice', 260:'sue', 1023:'max'} >>> roll.keys() [9450, 260, 1023] >>> roll.has_key(2600) False >>>

Python Functions
‡ A Python function can be either void or value returning, although the definition isn¶t identified as such.
± Technically, they are all value returning, since a void function returns the value none

‡ Each function defines a scope. Parameters and local variables are accessible in the scope; values in other functions are available only as parameters.

Function Syntax
Function definition def <name> (formal-parameters>): <body> Function call syntax: <name>.(<actual parameters>)

Later we will see how to use files and build traditional programs.>>> def square(x): return x * x #the blank line terminates the function #definition >>> square(10) 100 >>> z = 23 >>> square(z * 4) 8464 >>> square(z) 529 This function was typed in at the command line. .

x) print x y = input("Press any key to exit ") main() .py #A simple program illustrating chaotic behavior def main( ): print "a chaotic function" x = input("enter a number between 0 and 1: ") for i in range (10): x = 3.A main program file #File: chaos.9 * (1 .

dif >>> a.79 >>> sum(num1.b = SumDif(x.num2 = 3.Functions That Return Values >>> def sum(x.y return sum. num2) 82 >>> def SumDif(x.y): sum = x + y dif = x . b 17 -3 >>> .y) >>> a 17 >>> print a. y): sum = x + y return sum >>> num1.

and these pointers remain the same. only the things pointed to change! ± (don¶t worry about the subtleties here) .Parameters ‡ Parameters are passed by value.g. lists) act like reference parameters ± the value passed is a pointer to a list of pointers. so in general the actual parameters can¶t be changed by the function ± only their local copies ‡ Mutable objects (e..

479.7.Lists and Strings ± Review ‡ Strings are sequences of characters. µtree¶] ‡ String elements and list elements can be accessed by an index ‡ String elements can¶t be changed in place. 3. . lists are sequences of individual items ± aStr: ³47^abc´ ± aList: [µsue¶. list items can be.

Common Operations ‡ ‡ ‡ ‡ Slicing Concatenation & repetition Indexing Applying the length function : ± len(aList) or len(aStr) ‡ Iteration through elements ± >>> for i in range(len(myStr)): print myStr[i] ± >>> for i in range(len(myStr)): print myStr[i] .

'10'. but you can specify a different character: >>> myStr = '12/10/2008' >>> myStr. 'black'.split() ['The'.split('/') ['12'. 'cat'] ‡ split defaults to blank as the delimiter.Additional String Operations ‡ split: divides a list into a list of substrings ± >>> myStr = 'The fat black catµ >>> myStr. 'fat'. '2008'] .

you may want to convert some of the substrings to specific data types. float( ). and str( ).Strings ± Continued ‡ When using string functions begin by importing the string library: ± import string ‡ After you have split a string into a list of substrings. long( ). . The generic function is eval(<string>) and there are specific casts: int( ).

int(x[1]). '10'.float(x[2]) 12 10 2008.split('/') >>> x ['12'.Example >>> x = myStr. '2008'] >>> print eval(x[0]).0 .

File I/O ‡ <filevar> = open(<name>.close( ) .close( ) ± outfile.out´. ³w´) ‡ Files must also be closed: ± infile. ³r´) ± outfile = open(³data. and mode is either µr¶ or µw¶ ± infile = open(³data.in´. <mode>) where name is the name of the file on disk.

read: returns the remaining contents of the file as a multi-line string (lines in the file separated by \n) ‡ <filevar>.readline( ): returns next line as a string. includes the newline character (you can slice it off.Input Operations ‡ <filevar>. if needed) ‡ <filevar>.readlines( ): returns the remaining lines in the file. as a list of lines (each list item includes the newline character) .

Input/Output ‡ Output operations are less flexible. ± If you want to put a newline character in the file you must do so specifically ‡ Output formatting: % character ‡ <template-string> % (<value>) ‡ Possible formats are d (decimal). f (float) and s (string) . the only parameter is a string.

out".Example >>> outfile=open("C:\Temp\exmp. "w") >>> outfile. y)) >>> outfile.close() .write("this is the first line\n") >>> outfile.write('and this is the second\n') >>> outfile.write("the value of x is %d and y is %f" % (x.

Sign up to vote on this title
UsefulNot useful