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

Python Tutorial 1

Hi Everyone, Today I will write about python language. To get python, please visit Python Site and download the most stable version. I am using version 2.6. I would recommend using an installer instead of zip package as the installer will register python extension. You can use any kind of editor to write python code like notepad, WordPad, Notepad++ or any other. Once you have installed python, add python to your path. In windows, you can update environment variable to add python to your path. Once you have added python to your path, you can run python scripts simply by typing the file name like this:

D: \Scripts>HelloWorld.py

Python scripts have “.py” extension. To open python shell type python in command prompt like this

D:\Scripts>python

And you will get something like this:

====================================================================================

Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>>

You can type any python code in this shell to execute.

To run a script with interpreter, type “python –i ”. For example:

D:\Scripts>python –i HelloWorld.py

Basic:

The text written in quotes “” or ‘’ is string. Here are examples

>>> “This is a string”

‘This is a string’

>>> ‘This is also a string’

‘This is also a string’

Escape characters are special characters within string which have special meanings. The escape characters start with ‘\’. For example, ‘\n’, ‘\t’, ‘\r’, ‘\b’ etc. Quotes within string are also represented using escape sequences like “this is a \’ single quote” or “this is a \” double quote” and “this is a \\ backslash”.

String can be joined using “+”. For example, print “hello” + “ world”.

Format specifier in a string represents a placeholder for a value and “%” after string represents values for the placeholder. Note that the no. of placeholder should be equal to the no. of arguments specified after “%”. For Example:

print “%s name is %s %s” % (“My”, “Nabeel”, “Bukhari”)

In this example first %s is replaced by “My”, second with “Nabeel” and so on.

print “Sum of %d and %d is %d” % (4,5,9)

These are few format specifiers: “%d” for integers or long, “%c” for character, “%f” for float, “%e” for exponential, “%x” for hex, “%s” for strings etc

“print” is a function used for displaying text.

Data Types:

There are different data types, and each data type is used to represent different type of data and represent a specific range of data. For example: character, integers, floating point, Hexadecimal, Octal and strings. Character can be in single quote like: ‘a’, ‘A’ etc. Integers represent decimal values without fractional part like 1, 12, -512 etc. Floating point values contain fractional part as well and provide high precision like 4.53, -2.2222 etc. Hexadecimal values are base 16, it contains 0-9 and then A-F values like “1”, “8”, “A”,”B” etc. Octal values are base 8 and the values are from 0-7

Arithmetic Operators:

Arithmetic Operations are performed using arithmetic operators. For example: ‘+’, ’-‘, ‘*’, ‘/’, ‘%’ etc.

‘+’ is used for addition, ‘-‘ is used for subtraction, ‘*’ is used for multiplication, ‘/’ is used for division and ‘%’ is used for remainder.

For example: print 2+2, print 4-3, print 2*5, print 100/20, print 5%2 etc

The arithmetic operations are evaluated from left to right, however the operator precedence matters as we do in daily life like ‘*’ and ‘/’ operations are evaluated first and then ‘+’ and ‘-‘ operations are evaluated. We can make a operation evaluated first by using parentheses.

For example: (2*(2+5)-(3*19))

Variables:

We use names to store data in memory. These named memory locations are called variables. We can change the values of variables. Variables can be used to store different types of data. We can use any name for variable but there are few reserved words that we cannot use. Here is the list of these variables.

and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, yield

For Example:

MyString = “This is my first String”

And then I can use this string to print like this: print MyString. We can also store other type of values in strings like this:

FirstNumber = 5.0

SecondNumber = 2.0

Result = FirstNumber / SecondNumber

print “%d / %d = %0.2f” % (FirstNumber, SecondNumber, Result)

In this example, we are creating two variables of float type and storing its result in third variable which will be of same type. Python unlike other programming languages can understand the data type assigned and make the variable of that type. I like this feature the most J. You might have noticed that we set values for format specifiers in parentheses separated by comma. The reason for this is that format specifiers need values in the form of tuples, when the numbers of format specifiers are more than one.

Built-in Types:

There are different type of built-in types that can be used to store data. Three of the most commonly used are:

Tuples—Unchanging Sequences of Data:

Tuples are a sequence of values, each one accessible individually, and a tuple is a basic type in Python. You can recognize tuples when they are created because they’re surrounded by parentheses like this:

>>> print “A %s %s %s %s” % (“string”, “filled”, “by a”, “tuple”)

A string filled by a tuple

Tuples contain references to data such as strings and numbers. However, even though they refer to data, they can be given names just like any other kind of data.

>>> filler = (“string”, “filled”, “by a”, “tuple”)

>>> print “A %s %s %s %s” % filler

We can access (dereference) the values stored in a tuple using the index notation. The index starts with 0, 1 for the second value, and so on. The index of last element is one less than the total no of elements. For Example:

>>>>print filler[0]

>>>>print filler[3]

If we pass a value greater than count-1, where count is the no of elements in the tuple, it will raise an error.

We can find the length or count of elements using Len function.

>>>>print len(filler)

>>>>print filler[len(filler)-1]

In this example we accessed the last value of filler. Python makes life much easier, it provides another method to get the values in reverse easily. For example: to get the last value I can use filler[-1] and to get the second last value I can use filler[-2] and so on. J

Our tuples can be of multidimensional, for instance we can have a tuple which is accessed through another tuple. For example: this example uses make a 2 dimensional tuple.

>>> a = (“first”, “second”, “third”)

>>> b = (a, “b’s second element”)

>>> print “%s” % b[1]

>>> print “%s” % b[0][0]

>>> print “%s” % b[0][1]

>>> print “%s” % b[0][2]

One last thing about tuples is that they are immutable. It means that the value assigned cannot be changed like this: b[0][0] = “new”. This cannot be done, it will raise an error!

Lists—Changeable Sequences of Data:

Lists, like tuples, are sequences that contain elements referenced starting at zero. Lists are created by using square brackets. The elements of list can be accessed in the same manner:

>>> breakfast = [ “coffee”, “tea”, “toast”, “egg” ]

>> >print breakfast[0]

>>>print breakfast[-1]

The primary difference in using a list versus using a tuple is that a list can be modified after it has been

created. The list can be changed at any time:

>>> breakfast [0] = “sausages”

We can append new items at the end of the list using append method. For example :

>>> breakfast.append(“waffle”)

In case of multiple items, we pass the elements as a tuple, like this:

>>> breakfast.extend([“juice”, “decaf”, “oatmeal”])

If we want to append elements of a tuple to list, we will use the method extend to do so because if we use the append method, it will append the tuple to list not its element so do it as:

>>>breakfast.extend(filler);

If we need to remove an element from a list, we will use pop method. This method can be called to get the first item or we can give an integer index to get that indexed item. For example:

>>>firstitem = breakfast.pop()

Or using index

>>>seconditem = breakfast.pop(1)

Dictionaries—Groupings of Data Indexed by Name:

A dictionary is similar to lists and tuples. It’s another type of container for a group of data. Tuples and lists are indexed by their numeric order, where as dictionaries are indexed by names. These names can be letters, numbers, strings, or symbols. When you’re using dictionaries, Index names in dictionaries are called keys, and the values are called values. To create a fully specified (or you can think of it as a completely formed) dictionary—one with keys and values assigned at the outset—you have to specify each key and its corresponding value, separated by a colon, between the curly braces. For example:

>>> menu_specials = {“breakfast” : “canadian ham”, “lunch” : “tuna surprise”}

Another way of doing the same thing is:

>>> menus_specials = {}

>>> menus_specials[“breakfast”] = “canadian ham”

>>> menus_specials[“lunch”] = “tuna surprise”

The items of dictionary can also be accessed using index notation. The keys method of dictionary can be used to return all of its keys to you as a list so that you can examine them for the key (or keys) you are looking for, and the values method will return all of the values as a list.

>>> menu_specials.keys()

[‘lunch’, ‘breakfast’’]

>>> menu_specials.values()

[‘canadian ham’, ‘tuna surprise’]

To find if a key already exists in a dictionary, contains method can be used:

>>> menu_specials.__contains__(“test”)

>>> menu_specials.__contains__(“Brunch”)

We can get a specific set of values for tuple, list or dictionary. The set returned is of the same type as of the original set. For example: To get a new set of values from a tuple named filler ranging from 5 to 8, we can do it as:

>>> print filler[5:8]





Credits: