Thursday, 17 March 2016

Branching, Looping, and Exceptions in Python with code examples

Branching, Looping, and Exceptions in Python with code examples


Python has a very straightforward set of if/else statements:

if ("4.0" in GC_Ver_1):               
                Finalsessionanme = os.path.dirname(SQLiteName) + "\\" + SQLite_Prefix +"_"+ sessiondate
            elif ("4.5" in GC_Ver_1):
        Finalsessionanme = os.path.dirname(SQLiteName) + "\\" + sessionanme

The expressions that are part of if and elif statements can be comparisons (==, <, >, <=, >=, etc) or they can be any python object. In general, zero and empty sequences are False, and everything else is True. Python does not have a switch statement.


Python has two loops. The for loop iterates over a sequence, such as a list, a file, or some other series:

for TableName in gpsTableNames:
'''Updating position table...'''       
        if ("geo_positions_") in TableName[0]:       
            Position_TblsList.append (TableName[0])
            bFoundPositionTbl  = True             
        elif ("cameras") in TableName[0]      : bCameras      = True;           
        elif ("calibrations") in TableName[0] : bCalibrations = True
        elif ("metadata") in TableName[0]     : bMetadata     = True

The code above will print "spam" four times. The while loop executes while a condition is true:

counter = 5
while counter > 0:
     counter -= 1
With each iteration, the counter variable is reduced by one. This code executes until the expression is False, which in this case is when "counter" reaches zero.

Handling Exceptions

Python is different from languages like C or Java in how it thinks about er- rors. Languages like Java are “look before you leap” (LBYL) languages. That is, there is a tendency to check types and values to make sure that they are legal before they are used. Python, on the other hand, thinks of things more in a “easier to ask for forgiveness than permission”(EAFP) style. In other words, Pythonic style would be more likely to go ahead and try the operation and then handle any problems if they occur:
  if os.path.exists(SQLiteName):

            os.rename(SQLiteName, SQLiteFinalName)            
        except OSError as e:
            message = "Access-error on file \"" + str(SQLiteFinalName) + "\"!!! \n"
            print message           
   (message)  finally:      #this will always print      print "processing complete"
In this case, a list or sequence operation is attempted and if it fails because it's the wrong type, the except clause just deals with it. Otherwise the exception will be raised normally. Then, whether an exception happens or not the finally clause will be executed, usually to clean up after the operation in either case.
if <expression>:
If is the Conditional expression that only executes if True
The else is Used primarily as a catchall. If <expression> is False, then we fall into the else
The elif is used to test multiple conditions. 
for var in expression:
The For Loop for iterating over any sequence in the order that they appear
Break statement Breaks out of loop
Continue Ends  the current iteration of loop and goes back to top of loop
The try begins a block to check for exceptions
except <exception>:
Followed by Exception type being checked for, begins block of code to handle exception
Code that will be executed whether exception occurs or not

No comments: