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 'lada for carprice in prices items()print "price of"car"is"price |
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 can be handled by different code |
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 in re -module |
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}format(val_x=xval_y=yy is and is |
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 after writing is finished |
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)print "hellomy name is "self name |
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 say_hello(stu say_hello( |
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 student('martti'print stu namestu name 'jussi''martti |
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 the user |
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 base class stu say_hello(use new method proj stu get_thesis_project( |
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 sal self sal= the init method has one argument "selfand every method has at least one argument that "selfthis ,,selfargument is reference to the current object on which the method is being called this init method is called with the help of class constructor adding the member functions or methods to class we can add any number of functions or methods to the class as we like the function that is written inside the class is called "member function or methodwriting the method is quite similar to the ordinary function with just one difference the methods must have one argument named as "selfthis is the first argument that added to the beginning of parameters list the method or function definition is written inside the class as shown in the syntax#defining class class employeeclass header #declaring the class variable count= #defining the constructor def init (self, , )self name= self sal= employee count+= #adding the method to the class def dispemp(self)print("the employee name is:",self name,"salary is:",self salself variable the self argument refers to the current object python takes care of passing the current object as argument to the method while calling page |
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 object class abcdef init (self, )self balance= def disp(self)method with self argument print("the amount is:",self balanceob=abc( )ob disp(//method is called without argumentpython passes ,,obas argument at the background outputcreating the object from the class the procedure for creating the object is similar to the function call the class name and the arguments mentioned in the init method should be specified the syntax is as follow#creating the object emp =employee("ramesh", wherethe "employeeis class name this is used as constructor name the actual parameters are passed to the formal parameters present in the init method that in turn assigns to the instance variable this statement will create new instance (objectof classnamed emp we can access the members of objects using the object name as prefix along with dot operator creating the object or instance of the class is called "instantiationaccessing the members of the object once the object is createdit is very easy and straight forward to access the members of the object the object namedot operator and member name is used the syntax is as follow#accessing the member function emp dispemp(putting all the things together emptiest py #defining the class class employee'doc string#declare class variables count= |def page init (self, , )#constructor self name= |
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 classes data encapsulation is also known as data hiding it is the process of binding the data members and member function together into single unit this encapsulation defines different access levels for members of the class these access levels are specified as followany data or member function with access level "publiccan be accessed by any functions belonging to any class this is the lowest level of protection any data or member function with access level "privatecan be accessed by member functions of the same class in which it is declared this is the highest level of protection in pythonprivate variable are declared with the help of double underscore prefixed to the variable for examplebalanceis the private variable class variable and instance variable class can have variable defined in it basicallythese variables are of two typesclass variables and instance (objectvariable the class variables are always associated with class and instance variables are always associated with object the class variables are shared among all the objects there exists single copy of the class variables any change made to the class variable will be seen by all the objects the instance variables are not shared between objects change made to the instance variable will not reflect in other objects create class name "bankaccountand perform operations like deposit and withdraw from the same account save this class in module named account py and import it in the saving py file (use instance variableaccount py (module page testaccount py |
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 savings=account bankaccount( #depositing amount dep=float(input("enter amount to deposit")savings deposit(dep#withdraw amount =float(input("enter the amount to withdraw")savings withdraw(wprint("the remaining balance in your account is:",savings balanceoutputthe __del__(method (garbage collectionthe init (method initializes an object instance variables similarly we havedel (method which will do the opposite work this method frees the memory of the object when ti is no longer needed and the freed memory is returned back to the system this process is known as "garbage collectionthis method is called automatically when an object is going out of the scope we can use "delstatement for deleting the object as shown in the program #defining class and creating the object class abcdef init (self, )self balance= def disp(self)emthod with self argument print("the amount is:",self balancedef del (self)print("this object is deleted from the memory"ob=abc( )ob disp(#callinf the del (method del ob #if you try to call the method disp it raises error ob disp(outputinheritance inheritance is the one of the most and essential concept of the object oriented programming it is the process by which one class acquires the properties from one or more classes here the properties are the data members page and member functions the new classes are created from the existing classes the newly created class is called "derivedclass the |
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 relationship between base and derived class is called "kind of relationshipreusability the main reason to go to the concept of the inheritance is reusing the existing propertieswhich is called reusability the reusability permits us to get the properties from the previous classes we can also add the extra features to the existing class this is possible by creating new class from existing class the new class will have its own features and features acquired from the base class notethe new class will have its own properties and properties acquired from the base class inheriting classes in python the syntax to inherit the properties from one class to another will be as followclass derived_class (base_class)#body of the derived_class we can even write the base class name along with name of the module instead of writing it again example program to implement the inheritance (si py#single inheritances class adef add(self, , )self = self = print("the addition is:",self +self yclass ( )#single inheritance def sub(self, , )self = self = print("the subtraction 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( , page output |
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 the same methodwhen we create object from the derived classthe derived class version of the method is executed always this is known as method overriding example program for method overriding method overriding #method overriding -super(method class bcdef disp(self)print("base class method"class dc(bc)def disp(self)print("derived class method"ob=dc(ob disp(output derived class method types of inheritances python has various types of inheritances the process of inheritance can be either simple or complex this depends on the following pointsthe number of base classes used in the inheritance nested derivation based on the above points the inheritances are classified in to the six different types single inheritance multilevel inheritance multiple inheritance hierarchical inheritance hybrid inheritance multi-path inheritance single inheritance when only one class is derived from single base classsuch derivation called single inheritance it is the simplest form of inheritance the new class is termed as "derivedclass and the existing class is called "baseclass the newly created class contains the entire characteristics from its base class the example program is already is given above multilevel inheritance page is |
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-level inheritance multi-level inheritance class adef add(self, , )self = self = print("the addition is:",self +self yclass ( )#single inheritance def sub(self, , )self = self = print("the subtraction is:",self -self yclass ( )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( ,boutput enter value: enter value: the addition is the subtraction is the product is multiple inheritances when two or more base classes are used in the derivation of new classit is called "multiple inheritancethe derived class has all the properties of both class and class example program on multiple -inheritancemultiple inheritance class adef add(self, , )self = self = print("the addition is:",self +self yclass #single inheritance def sub(self, , )self = self = page output enter value: enter value: the addition is the subtraction is the product is |
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 splitting the base class into several sub classes is called"hierarchical inheritanceall the sub classes have the same properties of those in base class here the classes and acquire properties from the class hybrid inheritance combination of two or more types of inheritances is called "hybrid inheritancesometimes it is essential to derive class using more types of inheritance here there are classes abc and the class acquires the properties from ahence there exist single inheritance class acquires properties from (which is derived classand chence uses multiple inheritance here two different types of inheritances used aresingle and multiple example program on hybrid-inheritance hybrid-inheritance #types of inheritances class adef add(self, , )self = self = print("the addition is:",self +self yclass ( )#single inheritance def sub(self, , )self = page output enter value: enter value: the addition is the subtraction is the product is the division is |
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 object ob= (ob add( ,bob sub( ,bob mul( ,bob div( ,bmulti-path inheritance deriving class from two derived classes that are in turn derived from the same base class is called "multi-path inheritancein this context the derived class has two immediate base classeswhich are derived from one base classthere by forming the grandparentparent and child relationship the derived class inherits the features from base class (grandparentvia two separate paths thereforethe base class is also known as the indirect base class problem in multi-path inheritance (diamond problemthe derived class has the members of the base class twicevia parent and parent this results in ambiguity because duplicate set of members is created this is avoided in python using the dynamic algorithm ( and mrolinearizes the search order in such as way that left-to-right ordering is specified to avoid duplication composition or container or complex objects the complex objects are objects that are created from smaller or simple objects for examplea car is built from metal framean enginesome tyresa steering and several other parts the process of building complex objects from simpler objects is known as composition or containership the relationship is also called "has-aor "part-ofrelationship page |
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 the addition is the difference between inheritance and composition inheritance class inherits properties from another class the derived class may override base class functions the derived class may add data or functionality to the base class this represents "is-arelationship composition class contains objects of different classes as data members the container class cannot override the base class functions the container class cannot add anything to the contained class this represents "has-arelationship abstract classes and inheritances in pythonit is possible to create class which cannot be instantiated we can create class from which objects are not created this class is used as interface or template only the derived can override the features of the base class in pythonwe use "notimplementederrorto restrict the instantiation any class that has the notimplementederror inside the method definitions cannot be instantiated example program on abstract class#abstract class class adef disp(self)#abstract class method raise notimplementederror(class ( )def disp(self) page output the method of class the method of class |
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 and exceptions syntax errorthese errors are occur when we violate the rules of python and these are most common kind of errors that we get while we learn any new programming language examples( if >= syntaxerrorinvalid syntax here at the end ofif statement (:colon should be writtenerror will be generated otherwise violating indentationmissing (:colon at the end of loop statements etc exception erroreven if statement is syntactically correctit may still cause an error when executed such errors that occur at run-time are known as "exceptionsthe logical error may occur due to wrong algorithm or logic while solving particular problem these logical errors may lead to exceptions examples of exceptions are as followy+ nameerrorname 'yis not defined +'xtypeerrorunsupported operand type(sfor +'intand 'str *( / zerodivisionerrordivision by zero =[ , , [ indexerrorlist index out of range ={ :' ', :' ', :' ' [ keyerror problem with exceptionthe normal execution of the program will be abruptly terminated because of the exception in generaljust because of single run-time errorit is not reasonable to terminate the program abruptlyeven if program contains some legal lines to solve this problem the exceptions must be handled in python these exceptions are handled using the try and except blocks handling exceptions page |
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 statement(sbetween the try and except keywordsis executed if no exception occursthe except block is skipped and execution of the try statement is finished if an exception occurs during execution of the try blockthe rest of the block is skipped then if its type matches the exception named after the except keywordthe except block is executedand then execution continues after the try statement if an exception occurs which does not match the exception named in the except blockit is passed on to outer try statementsif no handler is foundit is an unhandled exception and execution stops with message example program exception py #program without exception handler =int(input("enter value") =int(input("enter value")print("the sum is:", +yprint("the suntraction is:", -yprint("the quotient is:", /yprint("the product is:", *yprint("the remainder is:", %yprint("the power of ^ si:", **youtput enter value enter value the sum is the suntraction is traceback (most recent call last)file " :/python/exception py"line in print("the quotient is:", /yzerodivisionerrordivision by zero exception py =int(input("enter value") =int(input("enter value")print("the sum is:", +yprint("the suntraction is:", -ytryprint("the quotient is:", /yprint("the remainder is:", %yexcept zerodivisionerrorprint("you should not divide number with zero"#legal code print("the product is:", *yprint("the power of ^ si:", **youtput enter value enter value the sum is the suntraction is you should not divide number with zero the product is the power of ^ si multiple except blocks python allows you to have multiple except blocks for single try block the block that matches with exception will be executed try block can be associated with one or more except block howeveronly one block will be executed at time page |
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 program to handle multiple exceptions mulexcept py #read the data tryx=int(input("enter value of :") =int(input("enter value of :")print( ** /yexcept (valueerror)print("check before you enter value:"except zerodivisionerrorprint("the value of should not be zero"except (keyboardinterrupt)print("please eneter number:"print("end of the program"output enter value of : enter value of : the value of should not be zero end of the program =restarte:/python/multiexcep py ======enter value of xcheck before you enter valueend of the program multiple exceptions in single except block it is possible to list number of exceptions in the except block when any one of the exception is raisedthen the except block is executed as shown in the program multexcept py #read the data tryx=int(input("enter value of :") =int(input("enter value of :")print( ** /yexcept (valueerror,zerodivisionerror,keyboardinterrupt )print("check before you enter values foer and should not be zero"print("end of the program" page output enter value of : enter value of : end of the program ======restarte:/python/multiexcep py ======enter value of : enter value of ycheck before you enter values for and should not be zero |
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 in such situationa better idea is to write handler that would catch all types of exceptions this must me the last one that can serve as wildcard syntax will be as followtrystatements except exception statements except exception statement exceptexecute this blockif an exception match is found example program testexcept py #read the data 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"exceptprint("unexpected error terminating program:"print("end of the program"output enter value of : enter value of yunexpected error programend of the program terminating the the the else clause the tryexcept block can also have an else clausewhichwhen present must follow all except blocks the statements in the else block only executedif the try clause does not raise an exception page |
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 successful "print("end of the program"output enter value of : enter value of : program execution is successful end of the program the raising the exception we can also deliberately raise the exception using the raise keyword the syntax is as followraise [exception-nameexample programtestexcept py tryx=int(input("enter value of :") =int(input("enter value of :")print( ** /yraise zerodivisionerror exceptprint("the value of should not be zero"output enter value of : enter value of : the value of should not be zero end of the program handling exceptions in invoked functions we can also handle exceptions inside the functions using the try-except blocks funexcep py def division(num,deno)tryr=num/deno print("the quotient is:",rexcept zerodivisionerrorprint("you cannot divide number by zero"#function call =int(input("enter value:") =int(input("enter value:")division( , page output enter value: enter value: you cannot divide number by zero ======restarte:/python/funexcep py =======enter value: enter value: the quotient is |
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 about programming has undergone many changes in the years since the first electronic computers required patch cables and switches to convey instructions from human to machine as is the case with many aspects of societychanges in computing technology provide computer scientists with growing number of tools and platforms on which to practice their craft advances such as faster processorshigh-speed networksand large memory capacities have created spiral of complexity through which computer scientists must navigate throughout all of this rapid evolutiona number of basic principles have remained constant the science of computing is concerned with using computers to solve problems you have no doubt spent considerable time learning the basics of problem-solving and hopefully feel confident in your ability to take problem statement and develop solution you have also learned that writing computer programs is often hard the complexity of large problems and the corresponding complexity of the solutions can tend to overshadow the fundamental ideas related to the problem-solving process this emphasizes two important areas for the rest of the text firstit reviews the framework within which computer science and the study of algorithms and data structures must fitin particularthe reasons why we need to study these topics and how understanding these topics helps us to become better problem solvers secondwe review the python programming language although we cannot provide detailedexhaustive referencewe will give examples and explanations for the basic constructs and ideas that will occur throughout the remaining |
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 that tools computer science is the study of problemsproblem-solvingand the solutions that come out of the problem-solving process given problema computer scientist' goal is to develop an algorithma step-by-step list of instructions for solving any instance of the problem that might arise algorithms are finite processes that if followed will solve the problem algorithms are solutions computer science can be thought of as the study of algorithms howeverwe must be careful to include the fact that some problems may not have solution although proving this statement is beyond the scope of this textthe fact that some problems cannot be solved is important for those who study computer science we can fully define computer sciencethenby including both types of problems and stating that computer science is the study of solutions to problems as well as the study of problems with no solutions it is also very common to include the word computable when describing problems and solutions we say that problem is computable if an algorithm exists for solving it an alternative definition for computer sciencethenis to say that computer science is the study of problems that are and that are not computablethe study of the existence and the nonexistence of algorithms in any caseyou will note that the word "computerdid not come up at all solutions are considered independent from the machine computer scienceas it pertains to the problem-solving process itselfis also the study of abstraction abstraction allows us to view the problem and solution in such way as to separate the so-called logical and physical perspectives the basic idea is familiar to us in common example consider the automobile that you may have driven to school or work today as drivera user of the caryou have certain interactions that take place in order to utilize the car for its intended purpose you get ininsert the keystart the carshiftbrakeaccelerateand steer in order to drive from an abstraction point of viewwe can say that you are seeing the logical perspective of the automobile you are using the functions provided by the car designers for the purpose of transporting you from one location to another these functions are sometimes also referred to as the interface on the other handthe mechanic who must repair your automobile takes very different point of view she not only knows how to drive but must know all of the details necessary to carry out all the functions that we take for granted she needs to understand how the engine workshow the transmission shifts gearshow temperature is controlledand so on this is known as the physical perspectivethe details that take place "under the hood the same thing happens when we use computers most people use computers to write documentssend and receive emailsurf the webplay musicstore imagesand play games without any knowledge of the details that take place to allow those types of applications to work they view computers from logical or user perspective computer scientistsprogrammerstechnology support staffand system administrators take very different view of the computer they introduction |
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 abstractionsometimes also called the clientdoes not need to know the details as long as the user is aware of the way the interface works this interface is the way we as users communicate with the underlying complexities of the implementation as another example of abstractionconsider the python math module once we import the modulewe can perform computations such as import math math sqrt( this is an example of procedural abstraction we do not necessarily know how the square root is being calculatedbut we know what the function is called and how to use it if we perform the import correctlywe can assume that the function will provide us with the correct results we know that someone implemented solution to the square root problem but we only need to know how to use it this is sometimes referred to as "black boxview of process we simply describe the interfacethe name of the functionwhat is needed (the parameters)and what will be returned the details are hidden inside (see figure what is programmingprogramming is the process of taking an algorithm and encoding it into notationa programming languageso that it can be executed by computer although many programming languages and many different types of computers existthe important first step is the need to have the solution without an algorithm there can be no program computer science is not the study of programming programminghoweveris an important part of what computer scientist does programming is often the way that we create representation for our solutions thereforethis language representation and the process of creating it becomes fundamental part of the discipline algorithms describe the solution to problem in terms of the data needed to represent the problem instance and the set of steps necessary to produce the intended result programming languages must provide notational way to represent both the process and the data to this endlanguages provide control constructs and data types what is computer science |
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 representation all data items in the computer are represented as strings of binary digits in order to give these strings meaningwe need to have data types data types provide an interpretation for this binary data so that we can think about the data in terms that make sense with respect to the problem being solved these low-levelbuilt-in data types (sometimes called the primitive data typesprovide the building blocks for algorithm development for examplemost programming languages provide data type for integers strings of binary digits in the computer' memory can be interpreted as integers and given the typical meanings that we commonly associate with integers ( and - in additiona data type also provides description of the operations that the data items can participate in with integersoperations such as additionsubtractionand multiplication are common we have come to expect that numeric types of data can participate in these arithmetic operations the difficulty that often arises for us is the fact that problems and their solutions are very complex these simplelanguage-provided constructs and data typesalthough certainly sufficient to represent complex solutionsare typically at disadvantage as we work through the problem-solving process we need ways to control this complexity and assist with the creation of solutions why study data structures and abstract data typesto manage the complexity of problems and the problem-solving processcomputer scientists use abstractions to allow them to focus on the "big picturewithout getting lost in the details by creating models of the problem domainwe are able to utilize better and more efficient problem-solving process these models allow us to describe the data that our algorithms will manipulate in much more consistent way with respect to the problem itself earlierwe referred to procedural abstraction as process that hides the details of particular function to allow the user or client to view it at very high level we now turn our attention to similar ideathat of data abstraction an abstract data typesometimes called an adtis logical description of how we view the data and the operations that are allowed without regard to how they will be implemented this means that we are concerned only with what the data is representing and not with how it will eventually be constructed by providing this level of abstractionwe are creating an encapsulation around the data the idea is that by encapsulating the details of the implementationwe are hiding them from the user' view this is called information hiding figure shows picture of what an abstract data type is and how it operates the user interacts with the interfaceusing the operations that have been specified by the abstract data type the abstract data type is the shell that the user interacts with the implementation is hidden one level deeper the user is not concerned with the details of the implementation the implementation of an abstract data typeoften referred to as data structurewill require that we provide physical view of the data using some collection of programming constructs and primitive data types as we discussed earlierthe separation of these two perspectives will introduction |
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 implementation independence allows the programmer to switch the details of the implementation without changing the way the user of the data interacts with it the user can remain focused on the problem-solving process why study algorithmscomputer scientists learn by experience we learn by seeing others solve problems and by solving problems by ourselves being exposed to different problem-solving techniques and seeing how different algorithms are designed helps us to take on the next challenging problem that we are given by considering number of different algorithmswe can begin to develop pattern recognition so that the next time similar problem ariseswe are better able to solve it algorithms are often quite different from one another consider the example of sqrt seen earlier it is entirely possible that there are many different ways to implement the details to compute the square root function one algorithm may use many fewer resources than another one algorithm might take times as long to return the result as the other we would like to have some way to compare these two solutions even though they both workone is perhaps "betterthan the other we might suggest that one is more efficient or that one simply works faster or uses less memory as we study algorithmswe can learn analysis techniques that allow us to compare and contrast solutions based solely on their own characteristicsnot the characteristics of the program or computer used to implement them in the worst case scenariowe may have problem that is intractablemeaning that there is no algorithm that can solve the problem in realistic amount of time it is important to be able to distinguish between those problems that have solutionsthose that do notand those where solutions exist but require too much time or other resources to work reasonably there will often be trade-offs that we will need to identify and decide upon as computer scientistsin addition to our ability to solve problemswe will also need to know and understand what is computer science |
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 the ideas from the previous section if you are new to python or find that you need more information about any of the topics presentedwe recommend that you consult resource such as the python language reference or python tutorial our goal here is to reacquaint you with the language and also reinforce some of the concepts that will be central to later python is moderneasy-to-learnobject-oriented programming language it has powerful set of built-in data types and easy-to-use control constructs since python is an interpreted languageit is most easily reviewed by simply looking at and describing interactive sessions you should recall that the interpreter displays the familiar prompt and then evaluates the python construct that you provide for exampleprint("algorithms and data structures"algorithms and data structures shows the promptthe print functionthe resultand the next prompt getting started with data we stated above that python supports the object-oriented programming paradigm this means that python considers data to be the focal point of the problem-solving process in pythonas well as in any other object-oriented programming languagewe define class to be description of what the data look like (the stateand what the data can do (the behaviorclasses are analogous to abstract data types because user of class only sees the state and behavior of data item data items are called objects in the object-oriented paradigm an object is an instance of class built-in atomic data types we will begin our review by considering the atomic data types python has two main built-in numeric classes that implement the integer and floating point data types these python classes are called int and float the standard arithmetic operations+-*/and *(exponentiation)can be used with parentheses forcing the order of operations away from normal operator precedence other very useful operations are the remainder (modulooperator%and integer division/note that when two integers are dividedthe result is floating point the integer division operator returns the integer portion of the quotient by truncating any fractional part introduction |
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 operands true for result to be true either operand true for result to be true negates the truth valuefalse becomes truetrue becomes false table relational and logical operators print( + * # print(( + )* # print( ** # print( / # print( / # print( // # print( % # print( / # print( // # print( % # print( ** the boolean data typeimplemented as the python bool classwill be quite useful for representing truth values the possible state values for boolean object are true and false with the standard boolean operatorsandorand not true true false false false or true true not (false or truefalse true and true true boolean data objects are also used as results for comparison operators such as equality (==and greater than (>in additionrelational operators and logical operators can be combined together to form complex logical questions table shows the relational and logical operators with examples shown in the session that follows print( = print( review of basic python |
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 convey meaning so that your program code is easier to read and understand python variable is created when name is used for the first time on the left-hand side of an assignment statement assignment statements provide way to associate name with value the variable will hold reference to piece of data and not the data itself consider the following sessionthe_sum the_sum the_sum the_sum the_sum the_sum true the_sum true the assignment statement the_sum creates variable called the_sum and lets it hold the reference to the data object (see figure in generalthe right-hand side of the assignment statement is evaluated and reference to the resulting data object is "assignedto the name on the left-hand side at this point in our examplethe type of the variable is integer as that is the type of the data currently being referred to by "the_sum if the type of the data changes (see figure )as shown above with the boolean value trueso does the type of the variable (the_sum is now of the type booleanthe assignment statement changes the reference being held by the variable this is dynamic characteristic of python the same variable can refer to many different types of data introduction |
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 sequence in python built-in collection data types in addition to the numeric and boolean classespython has number of very powerful builtin collection classes listsstringsand tuples are ordered collections that are very similar in general structure but have specific differences that must be understood for them to be used properly sets and dictionaries are unordered collections list is an ordered collection of zero or more references to python data objects lists are written as comma-delimited values enclosed in square brackets the empty list is simply lists are heterogeneousmeaning that the data objects need not all be from the same class and the collection can be assigned to variable as below the following fragment shows variety of python data objects in list [ , ,true, [ true my_list [ , ,true, my_list [ true note that when python evaluates listthe list itself is returned howeverin order to remember the list for later processingits reference needs to be assigned to variable since lists are considered to be sequentially orderedthey support number of operations that can be applied to any python sequence table reviews these operations and the following session gives examples of their use note that the indices for lists (sequencesstart counting with the slice operationmy_list[ ]returns list of items starting with the item indexed by up to but not including the item indexed by sometimesyou will want to initialize list this can quickly be accomplished by using repetition for examplemy_list [ my_list [ one very important aside relating to the repetition operator is that the result is repetition of references to the data objects in the sequence this can best be seen by considering the review of basic python |
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 removes and returns the last item in list removes and returns the ith item in list modifies list to be sorted modifies list to be in reverse order deletes the item in the ith position returns the index of the first occurrence of item returns the number of occurrences of item removes the first occurrence of item table methods provided by lists in python following sessionmy_list [ , , , [my_list]* print(amy_list[ ]= print(athe variable holds collection of three references to the original list called my_list note that change to one element of my_list shows up in all three occurrences in lists support number of methods that will be used to build data structures table provides summary examples of their use follow my_list [ true my_list append(falseprint(my_listmy_list insert( , print(my_listprint(my_list pop()print(my_listprint(my_list pop( )print(my_listmy_list pop( print(my_listmy_list sort(print(my_listmy_list reverse(print(my_listprint(my_list count( )print(my_list index( )my_list remove( print(my_listdel my_list[ print(my_list introduction |
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 the familiar "dotnotation for asking an object to invoke method my_list append(falsecan be read as "ask the object my_list to perform its append method and send it the value false even simple data objects such as integers can invoke methods in this way ( __add__( in this fragment we are asking the integer object to execute its add method (called __add__ in pythonand passing it as the value to add the result is the sum of coursewe usually write this as we will say much more about these methods later in this section one common python function that is often discussed in conjunction with lists is the range function range produces range object that represents sequence of values by using the list functionit is possible to see the value of the range object as list this is illustrated below range( range( list(range( )[ range( , range( list(range( , )[ list(range( , , )[ list(range( , ,- )[ the range object represents sequence of integers by defaultit will start with if you provide more parametersit will start and end at particular points and can even skip items in our first examplerange( )the sequence starts with and goes up to but does not include in our second examplerange( starts at and goes up to but not including range( performs similarly but skips by twos (again is not includedstrings are sequential collections of zero or more lettersnumbers and other symbols we call these lettersnumbers and other symbols characters literal string values are differentiated from identifiers by using quotation marks (either single or double"david'davidmy_name "davidmy_name[ review of basic python |
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 in field of size returns string in all lowercase returns string right-justified in field of size returns the index of the first occurrence of item splits string into substrings at s_char table methods provided by strings in python 'imy_name* 'daviddavidlen(my_name since strings are sequencesall of the sequence operations described above work as you would expect in additionstrings have number of methodssome of which are shown in table for examplemy_name 'davidmy_name upper('davidmy_name center( david my_name find(' ' my_name split(' '['da''id'of thesesplit will be very useful for processing data split will take string and return list of strings using the split character as division point in the examplev is the division point if no division is specifiedthe split method looks for whitespace characters such as tabnewline and space major difference between lists and strings is that lists can be modified while strings cannot this is referred to as mutability lists are mutablestrings are immutable for exampleyou can change an item in list by using indexing and assignment with string that change is not allowed introduction |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.