Вы находитесь на странице: 1из 6

Essentials for Scientic Computing: Introduction to Python Day 10

Ershaad Ahamed TUE-CMS, JNCASR

May 2012

Introduction

Python, unlike C and FORTRAN is not a compiled language. Python scripts can be written and run in exactly the same way as bash shell scripts. Python being an interpreted language, executes each line of code as it is encountered. Python is a complete multi-purpose programming language. Its syntax is elegant and easy to learn. One aspect that makes python very attractive is its large collection of standard modules. Modules are the python equivalent of libraries. By standard modules, we mean modules that are available in a standard python installation. The python language itself has only basic functionality. The large collection of modules make python useful for quickly writing scripts to perform useful functions. Python is free software.

Getting Started

Python is present by default on most Linux installations. The quickest way to start using python is to start the interactive python interpreter. In the interactive interpreter, you can type python statements and they are processed immediately. The following examples will illustrate that. Starting the interpreter. $ python Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> The >>> prompt means the interpreter is ready to accept python language statements. Our rst line of code >>> print "Hello, World" Hello, World >>>

Notice how the interpreter executed and produced output immediately after the python statement was entered. The line we just executed is the python statement to print the string Hello, World. String literals are always enclosed by single or double quotes. We can also print expressions which can look like. >>> print 1 + 3 4 >>> First, python evaluates the expression 1 + 3 which adds two integers and produces an integer result. The resulting integer is output by the print statement. An operator can have dierent meanings depending on the data type it operates on, for example the + operator performs concatenation on strings, and the * operator performs repetition. >>> print "First string" + "Second one" First stringSecond one >>> print "word" * 4 wordwordwordword >>> Variables in python can be easily created by using the assignment operator =. The right hand side of the assignment operator can also be expressions. Since the print statement also accepts variables: >>> mystring = "Hello, World" >>> print mystring Hello, World >>> mystring = 25 * 2 >>> print mystring 50 >>> In python the statement mystring = "Hello, World", creates a string Hello, World and associates the name mystring to it. In the second statement, the expression 25 * 2 is evaluated and the result is associated with the name mystring. Notice that after the rst assignment, mystring is associated with a string, and after the second assignment, mystring is associated with an integer. It is thus evident that python is a dynamic language and a variable is simply a name associated with a value. Unline C and FORTRAN, the type of the value that a variable is associated with need not be statically dened. Python has built-in support for complex numbers. >>> a = 3+4j >>> b = 1.2+11j >>> print a*b (-40.4+37.8j) >>> print a+b (4.2+15j) >>> print a-b (1.8-7j) >>> print a/b 2

(0.388761842535-0.230316889905j) >>> print a.real 3.0 >>> print a.imag 4.0 >>>

Basic Data Types

Besides the string, integer and oating point types, python supports some more data structures are built-in types.

3.1

Lists

Lists are analogous to arrays in other languages. But, python lists are far more exible, they can hold any combination of data types within a list. A few examples in the interactive interpreter. >>> mylist = [hello, 12, 23.5] >>> print mylist [hello, 12, 23.5] >>> print mylist[0] hello >>> print mylist[1] 12 >>> print mylist[2] 23.5 >>> print mylist[0:2] [hello, 12] >>> mylist[2] = "New String" >>> print mylist [hello, 12, New String] >>> print len(mylist) 3 >>> numlist = [1.2, 3.5, 33, 65] >>> print numlist * 2 [1.2, 3.5, 33, 65, 1.2, 3.5, 33, 65] >>> print numlist + numlist [1.2, 3.5, 33, 65, 1.2, 3.5, 33, 65] >>> Notice that list elements are indexed from zero. In the list above element 0 is a string, element 1 is an integer and element 2 is a oating point number. in the line print mylist[0:2] we use the list slice syntax, 0:2 means all elements between element 0 and element 2. Notice that 0:2 returns a list of 2 elements since element 2 is not included. To remember this imagine a C for loop that looks like for(i = 0; i < 2; i++), in which i takes values 0 and 1 before the loop ends. Assignment to list elements also works as expected. The built-in len() function returns the number of elements in the list. List values can be other lists also, which are called nested lists. 3

The bracket operator [] also works for strings >>> mystring = "Hello, World" >>> print mystring[0] H >>> print mystring[-1] d >>> print mystring[:7] Hello, >>> print mystring[7:] World >>> mystring[2] = x Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: str object does not support item assignment >>> print len(mystring) 12 >>> Negative indexes count from the end of the list, -1 being the last element. In the slice syntax, if no index is specied on the left of the colon it is implied to be the lowest index (zero), and if no index is specied on the right of the colon, it implies the higest index (length of the list - 1). Consequently a colon alone implies all elements. The last statement fails because strings, unlike lists are immutable, that is they cannot be modied once they are created.

3.2

Tuples

Tuples are a sequence type just like Lists and strings. Tuples are created by separating values with commas and enclosing them in parentheses. A trailing comma is necessary when creating a tuple of one element so that python does not interpret it as an expression. >>> mytuple = (1, 4.5, "World") >>> print mytuple (1, 4.5, World) >>> print mytuple[2] World >>> mytuple[1] = 23 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: tuple object does not support item assignment >>> not_a_tuple = (24) >>> print not_a_tuple 24 >>> a_tuple = (24,) >>> print a_tuple (24,) >>> As is evident from above, tuples are an immutable type.

3.3

Sets

Sets are a sequence type that is unordered and does not have duplicates. Sets are mutable and elements can be added to an existing set. But if a set already has an identical element, a duplicate is not added. Sets are created by passing a sequence type to the set() built-in function. >>> mylist = [1, 3, 4, 1, wordA, wordB, wordA] >>> mytuple = (wordC, 4.5, 77, (1,2), 12, (1,2)) >>> mystring = "queue" >>> print mylist [1, 3, 4, 1, wordA, wordB, wordA] >>> print mytuple (wordC, 4.5, 77, (1, 2), 12, (1, 2)) >>> print mystring queue >>> myset = set(mylist) >>> print myset set([1, 3, 4, wordA, wordB]) >>> myset = set(mytuple) >>> print myset set([4.5, (1, 2), 12, 77, wordC]) >>> myset = set(mystring) >>> print myset set([q, e, u]) >>> Sets support set operations such as union, intersection, dierence and symmetric dierence. The operators are Dierence. Returns elements that are in one set but not in the other | Logical OR. Elements in either one set or the other. & Logical AND. Elements that are in both sets. ^ Logical Exclusive OR. Elements in either set but not both. >>> mysetA = set([apple, mango, strawberry]) >>> mysetB = set([mango, pears, grapes]) >>> print mysetA - mysetB set([strawberry, apple]) >>> print mysetB - mysetA set([pears, grapes]) >>> print mysetA | mysetB set([strawberry, mango, apple, grapes, pears]) >>> print mysetA & mysetB set([mango]) >>> print mysetA ^ mysetB 5

set([strawberry, pears, grapes, apple]) >>>

3.4

Dictionaries

We have seen that sequence types like Lists, Tuples and Strings are indexed by an integer. Dictionaries on the other hand are indexed by a key, which can be any immutable value. Dictionaries are created by placing a comma separated list of key:value pairs between braces. >>> phone_nos = {"home":"988988988", "office":"0803332222", "integer":25} >>> print phone_nos[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 0 >>> print phone_nos[home] 988988988 Dictionaries can also be created from lists of tuples. >>> myinfo = [("name","ershaad"), ("phone","98989898")] >>> mydict = dict(myinfo) >>> print mydict {phone: 98989898, name: ershaad} >>> print mydict["name"] ershaad >>>

3.5

Sequence Unpacking

Python allows sequences of variables to be assigned to, that is they can be the left hand side of an assignment operator. It can be used to extract values from a sequence into a number of variables. >>> mylist = ["one", "two", "three"] >>> a, b, c = mylist >>> print a one >>> print b two >>> print c three >>> a = 4 >>> b = 5 >>> a, b = b, a >>> print a, b 5 4 >>>

Вам также может понравиться