id
int64
0
25.6k
text
stringlengths
0
4.59k
12,400
www python org langtangen"python scripting for computational science"springer www scipy org matplotlib sourceforge net mpi py scipy org
12,401
12,402
syntax and code structure data types and data structures control structures functions and modules text processing and io
12,403
typicallya py ending is used for python scriptse hello pyhello py print "hello world!scripts can be executed by the python executablepython hello py hello world
12,404
the interactive interpreter can be started by executing python without argumentspython python (# jul : : [gcc (red hat - )on linux type "help""copyright""creditsor "licensefor more information print "hellohello useful for testing and learning
12,405
variable and function names start with letter and can contain also numbers and underscorese "my_var""my_var python is case sensitive code blocks are defined by indentation comments start by sign example py example if increase print("increasing "elsex print "decreasing xprint(" is processed"
12,406
python is dynamically typed language no type declarations for variables variable does have type incompatible types cannot be combined example py print "starting examplex for in range( ) + "resultz error
12,407
integers floats complex numbers basic operations and and *implicit type conversions be careful with integer division ** ( ( - / /
12,408
strings are enclosed by or multiline strings can be defined with three double quotes strings py "very simple strings 'same simple strings "this isn' so simple strings 'is this "complexstring? """this is long string expanding to multiple linesso it is enclosed by three "' ""
12,409
and operators with strings"strings can be "combined'strings can be combined"repeat 'repeatrepeatrepeat
12,410
lists and tuples dictionaries
12,411
python lists are dynamic arrays list items are indexed (index starts from list item can be any python objectitems can be of different type new items can be added to any place in the list items can be removed from any place of the list
12,412
defining lists my_list [ "egg" my_list [ [ ] accessing list elements my_list [ my_list [ [ my_list [- modifying list items my_list [- my_list [ 'egg'
12,413
adding items to list accessing list elements and operators with lists my_list [ my_list append( my_list [ my_list insert( , my_list [ my_list [ my_list extend(my_list my_list [ [ [ [ [ [
12,414
it is possible to access slices of lists removing list items my_list [ my_list [ : [ my_list [: [ my_list [ :[ my_list [ : : [ my_list [::- [ second my_list pop( my_list [ second
12,415
tuples are immutable lists tuples are indexed and ( [ sliced like listsbut cannot traceback (most recent call last)file ""line in be modified typeerror'tupleobject does not support item assignment
12,416
dictionaries are associative arrays unordered list of key value pairs values are indexed by keys keys can be strings or numbers value can be any python object
12,417
creating dictionaries accessing values adding items grades {'alice 'john 'carl grades {'john' 'alice' 'carl' grades['john' grades['linda' grades {'john' 'alice' 'carl' 'linda' elements {elements['fe' elements {'fe'
12,418
python variables are my_list [ , , , my_list my_list always references my_list and my_list are my_list [ references to the same list my_list modifying my_list changes also my_list [ copy can be made by slicing the whole list my_list my_list [:my_list [- my_list [ my_list [
12,419
object is software bundle of data (=variablesand related methods data can be accessed directly or only via the methods (=functionsof the object in pythoneverything is object methods of object are called with the syntaxobj method methods can modify the data of object or return new objects
12,420
python syntaxcode blocks defined by indentation numeric and string datatypes powerful basic data structureslists and dictionaries everything is object in python python variables are always references to objects
12,421
12,422
if else statements while loops for loops exceptions
12,423
if statement allows one to execute code block depending on condition code blocks are defined by indentationstandard practice is to use four spaces for indentation example py if + numbers[ boolean operators==!=>=<
12,424
there can be multiple branches of conditions example py if = print " is zeroelif print " is negativeelif print " is largeelseprint " is something completely differentpython does not have switch statement
12,425
while loop executes code block as long as an expression is true example py cubes {cube while cube cubes[xcube + cube **
12,426
for statement iterates over the items of any sequence ( listexample py cars ['audi''bmw''jaguar''lada'for car in carsprint "car is "car in each passthe loop variable car gets assigned next value from the sequence value of loop variable can be any python object
12,427
many sequence-like python objects support iteration dictionary"nextvalues are dictionary keys example py prices {'audi 'bmw 'lada for car in pricesprint "car is "car print "price is "prices[car(later onfile as sequence of lines"nextvalue of file object is the next line in the file
12,428
items in the sequence can be lists themselves example py coordinates [[ ][ ][ ]for coord in coordinatesprint " ="coord[ ]" ="coord[ values can be assigned to multiple loop variables example py for xy in coordinatesprint " =" " =" dictionary method items(returns list of key-value pairs example py prices {'audi' 'bmw 'la...
12,429
break out of the loop example py example py while truex + cube ** if cube break sum for in pricessum + if sum print "too muchbreak continue with the next iteration of loop example py example py - cube while cube + if continue cube ** sum for in pricesif continue sum +
12,430
exceptions allow the program to handle errors and other "unusualsituations in flexible and clean way basic conceptsraising an exception exception can be raised by user code or by system handling an exception defines what to do when an exception is raisedtypically in user code there can be different exceptions and they ...
12,431
exception is catched and handled by try except statements example py my_list [ tryfourth my_list[ except indexerrorprint "there is no fourth elementuser code can also raise an exception example py if solver not in ['exact''jacobi''cg']raise runtimeerror('unsupported solver'
12,432
useful python idiom for creating lists from existing ones without explicit for loops creates new list by performing operations for the elements of listnewlist [op(xfor in oldlistnumbers range( squares [ ** for in numberssquares [ conditional statement can be included odd_squares [ ** for in numbers if = odd_squares [
12,433
12,434
defining functions calling functions importing modules
12,435
function is block of code that can be referenced from other parts of the program functions have arguments functions can return values
12,436
function py def add(xy)result return result sum add(uvname of function is add and are arguments there can be any number of arguments and arguments can be any python objects return value can be any python object
12,437
functions can also be called using keyword arguments function py def sub(xy)result return result res sub( res sub( = = keyword arguments can improve readability of code
12,438
it is possible to have default values for arguments function can then be called with varying number of arguments function py def add(xy= )result return result sum add( sum add(
12,439
as python variables are always referencesfunction can modify the objects that arguments refer to def switch(mylist)tmp mylist[- mylist[- mylist[ mylist[ tmp [ , , , , switch( [ side effects can be wanted or unwanted
12,440
modules are extensions that can be imported to python to provide additional functionalitye new data structures and data types functions python standard library includes several modules several third party modules user defined modules
12,441
import statement example py import math math exp( import math as exp( from math import exppi exp( pi from math import exp( sqrt(piexp from math import exp won' workexp is now function
12,442
it is possible to make imports from own modules define function in file mymodule py mymodule py def incx( )return + the function can now be imported in other py filestest py test py import mymodule from mymodule import incx mymodule incx( incx(
12,443
functions help in reusing frequently used code blocks functions can have default and keyword arguments additional functionality can be imported from modules
12,444
12,445
working with files reading and processing file contents string formatting and writing to files
12,446
opening filemyfile open(filenamemodereturns handle to the file fp open('example txt'' '
12,447
file can opened for readingmode=' (file has to existwritingmode=' (existing file is truncatedappendingmode='aclosing file myfile close(example py open file for reading infile open('input dat'' 'open file for writing outfile open('output dat'' 'open file for appending appfile open('output dat'' 'close files infile close...
12,448
single line can be read from file with the readline(function infile open('inp'' 'line infile readline(it is often convenient to iterate over all the lines in file infile open('inp'' 'for line in infileprocess lines
12,449
generallya line read from file is just string string can be split into list of stringsinfile open('inp'' 'for line in infileline line split(fields in line can be assigned to variables and added to lists or dictionaries for line in infileline line split(xy float(line[ ])float(line[ ]coords append(( , )
12,450
sometimes one wants to process only files containing specific tags or substrings for line in infileif "forcein lineline line split(xyz float(line[ ])float(line[ ])float(line[ ]forces append(( , , )other way to check for substringsstr startswith()str endswith(python has also an extensive support for regular expressions ...
12,451
output is often wanted in certain format the string object has format method for placing variables within string replacement fields surrounded by {within the string xy print " is { and is { }format(xyx is and is print " is { and is { }format(xyy is and is possible to use also keywordsprint " is {val_yand is {val_x}form...
12,452
presentation of field can be specified with { :[ ] ][ ] is optional minimum width gives optional precision (=number of decimalst is the presentation type some presentation types string (normally omittedd integer decimal floating point decimal floating point exponential print " is { : fand is { : }format(xyx is and is
12,453
data can be written to file with print statements file objects have also write(function the write(does not automatically add newline output py outfile open('out'' 'print >outfile"headerprint >outfile"{ : { : }format(xyoutfile open('out'' 'outfile write("header\ "outfile write("{ : { : }format(xy)file should be closed a...
12,454
print is function in differences py print "the answer is" * print("the answer is" * print >>sys stderr"fatal error print("fatal error"file=sys stderr in some dictionary methods return "viewsinstead of lists keys() sort(does not workuse sorted(dinstead for more detailssee
12,455
files are opened and closed with open(and close(lines can be read by iterating over the file object lines can be split into lists and check for existence of specific substrings string formatting operators can be used for obtaining specific output file output can be done with print or write(
12,456
math "non-basicmathematical operations os operating system services glob unix-style pathname expansion random generate pseudorandom numbers pickle dump/load python objects to/from file time timing information and conversions xml dom xml sax xml parsing many more
12,457
python is dynamic programming language flexible basic data structures standard control structures modular programs with functions and modules simple and powerful test processing and file / rich standard library
12,458
12,459
basic concepts classes in python inheritance special methods
12,460
oop is programming paradigm data and functionality are wrapped inside of an "objectobjects provide methods which operate on (the data ofthe object encapsulation user accesses objects only through methods organization of data inside the object is hidden from the user
12,461
string as an object data is the contents of string methods could be lower/uppercasing the string two dimensional vector data is the and components method could be the norm of vector
12,462
in python everything is object exampleopen function returns file object data includes the name of the file open('foo'' ' name 'foomethods of the file object referred by are read() readlines() close()also lists and dictionaries are objects (with some special syntax
12,463
class defines the objecti the data and the methods belonging to the object there is only single definition for given object type instance there can be several instances of the object each instance can have different databut the methods are the same
12,464
when defining class methods in python the first argument to method is always self self refers to the particular instance of the class self is not included when calling the class method data of the particular instance is handled with self students py class studentdef set_name(selfname)self name name def say_hello(self)p...
12,465
students py class studentdef set_name(selfname)self name name def say_hello(self)print "hellomy name is "self name creating an instance of student stu student(calling method of class stu set_name('jussi'creating another instance of student stu student(stu set_name('martti'the two instances contain different data stu sa...
12,466
data can be passed to an object at the point of creation by defining special method __init__ __init__ is always called when creating the instance students py class studentdef __init__(selfname)self name name in pythonone can also refer directly to data attributes from students import student stu student('jussi'stu stud...
12,467
classes can be used for -struct or fortran-type like data structures students py class studentdef __init__(selfnameage)self name name self age age instances can be used as items in lists stu student('jussi' stu student('martti' student_list [stu stu print student_list[ age
12,468
generallyoop favours separation of internal data structures and implementation from the interface in some programming languages attributes and methods can be defined to be accessible only from other methods of the object in pythoneverything is public leading underscore in method name can be used to suggest "privacyfor ...
12,469
new classes can be derived from existing ones by inheritance the derived class "inheritsthe attributes and methods of parent the derived class can define new methods the derived class can override existing methods
12,470
inherit py class studentclass phdstudent(student)override __init__ but use __init__ of base classdef __init__(selfnameagethesis_project)self thesis thesis_project student __init__(selfnameagedefine new method def get_thesis_project(self)return self thesis stu phdstudent('pekka' 'theory of everything'use method from the...
12,471
class can define methods with special names to implement operations by special syntax (operator overloadingexamples __add____sub____mul____div__ for arithmetic operations (+-*/__cmp__ for comparisonse sorting __setitem____getitem__ for list/dictionary like syntax using [
12,472
defining the __init__ method (constructorthere is special method init which is used to initialize the instance variables or data members of the class this is also called as "constructorit is defined as followsdef init (selfns)constructorwhere and are parameters self name= #initialization of instance variablesname and s...
12,473
even if the method does not contain the argumentpython passes this "current objectthat called the method as argumentwhich in turn is assigned to the self variable in the method definition similarly method defined to take one argument will actually take two argumentsself and parameter #defining class and creating the ob...
12,474
self sal= employee count+= def dispemp(self)print(the name is:",self name,"sal is :",self sal#end of the class #creating object emp =employee("ram", emp =employee("raju", #access the member function emp dispemp(emp dispemp(print("the number of employees are:",employee countoutputdata abstraction and hiding through clas...
12,475
class bankaccountdef init (self,bal)self balance=bal def deposit(self,bal)self balance+=bal def withdraw(self,amount)if(self balance>=amount)self balance-=amount elseprint("insufficient amount in your account"import account #here account is the module contains bankaccount class #create object from bankaccount class sav...
12,476
existing class is called "baseclass the derived class also called with other names such as sub classchild class and descendent the existing class is also called with other names such as super classparent class and ancestor the concept of inheritance thereforefrequently used to implement is- relationship the relationshi...
12,477
polymorphism and method overriding polymorphism in its simple terms refers to have different forms it is the key feature of oop it enables program to assign different version of the function based on the context in pythonmethod overriding is way to implement polymorphism if the base class and derived classes are having...
12,478
the process of deriving new class from derived class is known as "multilevel inheritancethe intermediate derived class is also known as middle base class is derived from the class is derived from here is called intermediate base class the series of classes ab and is called "inheritance pathwayexample program on multi-l...
12,479
subtraction print("the is:",self -self #multiple inheritance class ( , )def mul(self, , )self = self = print("the product is:",self *self #read data into and =int(input("enter value:") =int(input("enter value:")#create object from derived object ob= (ob add( ,bob sub( ,bob mul( ,bhierarchical inheritance the process of...
12,480
self = print("the subtraction is:",self -self yclass cdef mul(self, , )self = self = print("the product is:",self *self #hybrid inheritance class ( , )def div(self, , )self = self = print("the division is:",self /self #read data into and =int(input("enter value:") =int(input("enter value:")#create object from derived o...
12,481
example program on compositioncomposition class def add(self, , )self = self = print("the addition is:",self +self #composition class def sub(self, , )self = (#object of class (self = self = print("the subtraction is:",self -self yself add( , #calling the method of another class ob= (ob sub( , output the subtraction is...
12,482
print("the method of class "class ( )def disp(self)print("the method of class "#create object #ob= (we cannot create object #ob disp(#we cannot call the method ob = (ob disp(ob = (ob disp(error and exceptionsdifference between an error and exception there are (at leasttwo distinguishable kinds of errorssyntax errors an...
12,483
the statements that can raise the exception are placed inside the try blockand the code that handles is placed inside except block here try and except are keywords the syntax for tryexcept can be as given bellowtrystatements except exceptionnamestatements the try statement works as follows firstthe try block (the state...
12,484
the syntax for multiple except blocks for single try will be as followtryoperations are done in this block except exception if exception is matchedthis block will be executed except exception if exception is matchedthis block will be executed elseif there is no exception matchedthis block will be executed example progr...
12,485
end of the program except block without exception we can even specify except block without mentioning any exception in large software programsmany timesit is difficult to anticipate (guessingall types of possible exceptional conditions therefore programmer may not be able to write different handler for every exception ...
12,486
testexcept py tryx=int(input("enter value of :") =int(input("enter value of :")print( ** /yexcept (typeerror)print("choose the correct type of value:"except (zerodivisionerror)print("the value of should not be zero"except (valueerror)print("unexpected error terminating program:"elseprint("program execution is successfu...
12,487
contents
12,488
one introduction objectives to review the ideas of computer scienceprogrammingand problem-solving to understand abstraction and the role it plays in the problem-solving process to understand and implement the notion of an abstract data type to review the python programming language getting started the way we think abou...
12,489
what is computer sciencecomputer science is often difficult to define this is probably due to the unfortunate use of the word "computerin the name as you are perhaps awarecomputer science is not simply the study of computers although computers play an important supporting role as tool in the disciplinethey are just tha...
12,490
figure procedural abstraction must know the details of how operating systems workhow network protocols are configuredand how to code various scripts that control function they must be able to control the low-level details that user simply assumes the common point for both of these examples is that the user of the abstr...
12,491
control constructs allow algorithmic steps to be represented in convenient yet unambiguous way at minimumalgorithms require constructs that perform sequential processingselection for decision-makingand iteration for repetitive control as long as the language provides these basic statementsit can be used for algorithm r...
12,492
figure abstract data type allow us to define the complex data models for our problems without giving any indication as to the details of how the model will actually be built this provides an implementationindependent view of the data since there will usually be many different ways to implement an abstract data typethis...
12,493
solution evaluation techniques in the endthere are often many ways to solve problem finding solution and then deciding whether it is good one are tasks that we will do over and over again review of basic python in this sectionwe will review the programming language python and also provide some more detailed examples of...
12,494
operation name less than greater than less than or equal greater than or equal equal not equal logical and logical or logical not operator <>==and or not explanation less than operator greater than operator less than or equal to operator greater than or equal to operator equality operator not equal operator both operan...
12,495
figure variables hold references to data objects figure assignment changes the reference print(( > and ( < )identifiers are used in programming languages as names in pythonidentifiers start with letter or an underscore ( )are case sensitiveand can be of any length remember that it is always good idea to use names that ...
12,496
operation name indexing concatenation repetition membership length slicing operator in len explanation access an element of sequence combine sequences together concatenate repeated number of times ask whether an item is in sequence ask the number of items in the sequence extract part of sequence table operations on any...
12,497
method name use append insert pop pop sort reverse del index count remove a_list append(itema_list insert( ,itema_list pop(a_list pop(ia_list sort(a_list reverse(del a_list[ia_list index(itema_list count(itema_list remove(itemexplanation adds new item to the end of list inserts an item at the ith position in list remov...
12,498
you can see that some of the methodssuch as popreturn value and also modify the list otherssuch as reversesimply modify the list with no return value pop will default to the end of the list but can also remove and return specific item the index range starting from is again used for these methods you should also notice ...
12,499
method name use center count a_string center(wa_string count(itemljust a_string ljust(wlower rjust a_string lower(a_string rjust(wfind a_string find(itemsplit a_string split(s_charexplanation returns string centered in field of size returns the number of occurrences of item in the string returns string left-justified i...