Meebo Chat Bar

Sunday, August 2, 2009

Python Tutorial 2

Decision Making:

Sometimes we want to make decision like if a number is greater or equal or less than other or to see if two lists contain same items or the username and password match. We can make decision in python using if keyword. If we want to see if a number is greater than 5:

>>>if Number > 5:

print “Done”

This case only checks if a specific number is greater than 5. We can also do something if a condition is false. For example:

If Number >5 :

print “Done”

else:

print “Pending”

You should care about the indentation of the next statement after if and else and also the colon at the end of these statements. If you will not care about the indentation, the compiler will raise an error about the indentation it cannot understand. To make multiple checks, we can take help of elif keyword.

If Number <= 5:

print “Done”

elif Number > 6:

print “Well Done”

else:

print “pending”

We can also place if statements inside other if statements. Nested statements also follow the concept of indentation.

If Number > 5:

print “checking for better!”

If Number == 6:

print “Well Done”

else:

print “Pending”

Repetition:

Sometimes we want to do something again and again or to go through the list of items we need some mechanism to do it easily. Doing it manually will make it trouble if the items to work on are great in size. The two operations that enable you to initiate and control repetitive tasks are the while and for operations. The while operation tests for one truth condition, so it will be referred to as while… :.

>>> ingredients = omelet_ingredients.keys()

>>> while len(ingredients) > 0:

current_ingredient = ingredients.pop()

print omelet_ingredients[current_ingredient]

In this example, we first assign the keys in this dictionary to ingredients variable and then we use while operation to see if the len of ingredient list is greater than zero (i.e if the list is not empty), if it is not, then we pop the first item and assign this key to current_ingredient and in last statement use this key to get the value.

The for operation uses each value from within a list, so it will be referred to as for ... in ... :.

>>> for ingredient in omelet_ingredients.keys():

print omelet_ingredients[ingredient]

In this example, we say that for each ingredient in omelet_ingredients.keys() which is a list, get this ingredient key and then get value for that key.

We can use break to stop repetition. For instance if I want to say that if this ingredient is present in the keys then stop:

>>>for ingredient in omelet_ingredients.keys():

if ingredient == “test”:

break

To skip for a specific key or item, we can use continue keyword:

>>>for ingredient in omelet_ingredients.keys():

if ingredient == “test”:

continue

Handling Errors:

Whenever errors occur, it has a lot of information about what happened and why it happened. A “try:” statement sets up a situation in which an “except:” statement can follow it. Each “except:” statement handles the error, which is formally named an exception, that was just raised when Python evaluated the code within the “try:” statement instead of failing.

>>> try:

if omelet_ingredients [“butter”] > 3:

print “Sure”

except KeyError:

print “Aww, there’s no butter. Let’s go shopping”

This example has two major statements, try and except. If an error occurs because of key “butter” not found in “omelet_ingredients”, then it will be handled by except block. It will not raise a compile time error like we will if it’s not handled. We can also get the error information and print it or use it as needed.

>>> try:

if omelet_ingredients [“butter”] > 3:

print “Sure”

except KeyError, error:

print “Aww, there’s no %s. Let’s go shopping” % error

The will raise an exception but we have handled it. The name error after “KeyError” will be used by python to set reference of the string which contains any information about the error. If you have an exception that you need to handle, but you want to handle it by not doing anything (for cases in which failure isn’t actually a big deal), Python will let you skip that case by using the special word pass:

>>> try:

if omelet_ingredients [“butter”] > 3:

print “Sure”

except KeyError, error:

print “Aww, there’s no %s. Let’s go shopping” % error

except TypeError:

pass

If you need to indicate that a particular error has occurred, you may want to use one of the errors you’ve already encountered to indicate, through the function that’s being called, what has gone wrong. There is a counterpart to the try: and except: special words: the raise ... command. A good time to use the raise ... command might be when you’ve written a function that expects multiple parameters but one is of the wrong type. When you use “raise ...” you provide a message that an “except ... :” clause can capture for display

No comments:

Post a Comment