Header Ads

Python - A Quick Tutorial


Whether you have used it or not, Python is probably a language you all have heard of. The reason is simple; this language has friends in high places.



Python is a favored language at Google, and was one of the first languages supported in its Google App Engine platform for developing web applications. It is also the language in which Google choose to write its GoogleCL command line interface for Google services. Many organization use Python both internally and in shipping products. The popular Civilization IV game by Firaxis for example, makes extensive use of Python for the game mechanics: Industrial Light and Magic too use Python, as does Yahoo. Blender, possibly the most popular free and open source software for creating and editing 3D content, makes significant use of Python. While Firefox itself isn't written in Python, its build system makes extensive use of Python.

So why so much love for Python? Well, because it is fast, it is free and open source, and best of all it is easy to learn. Python is portable, and is available for multiple platforms, Windows, Linux, Mac OS, and is embeddable in other products. For someone new to programming, Python is a great language to start with, and will likely stay with you even as you learn other languages.

Python is a high level language, which means most operations you wish to perform have libraries and can be handled in just a few lines. You can, for example, have a simple web server up and running in fewer than 100 lines of code, thanks to the HTTPServer class.

Python is extensible, and one will find thousands of modules which extend its functionality. Python is scalable, considering that You Tube is almost entirely Python! Most of the modules that come with Python are actually written in C / C++ so they run at native speeds, and your programs generally run faster than those of other interpreted programming languages.

Python is good at interfacing with other programming languages such as Java and C++ making it a great language for programming higher level features of an application, while keeping performance-critical functions in native code. This enables Python developers to easily use C I C++ libraries such as Qt / GTK + and other.

Python is also peculiar. Unlike most programming languages, where white-spaces and tabs are used simply for code formatting and discarded otherwise, Python uses these elements as part of the code structure. Python uses spacing instead of ‘{‘ brackets or text to denote blocks of code.

In one sentence, Python is a fast, interpreted, Object-Oriented, Dynamic, free, Open Source, powerful, extensible, modular, high-level, portable programming language that is easy to learn, and which has a powerful library, good documentation, a large number of third party modules, and a sense of humor.

Learning Python

Whether you are simply looking for a language to automate simple tasks or, process data in bulk, or if you want to prototype or write an entire application Python is a great tool for the job.

Since Python enforces code indentation, and makes it part of the language, Python code is quite easy to understand. Look at the following code sample:

a, b = 0, 1
while a < 1000000:
a, b = b, a+b
print (a)

By looking at this program it is quite easy to understand what it does. The first line simultaneously assigns the value 0 to a, and 1 to b. The second line tells us that the subsequent code needs to be repeated while the condition following it holds true. The third line is clear in that it prints the value of the variable b. The final line, sets the value of a to b and the value of b to a+b.

Some of you may be aware of the mathematical significance of this code, but for those who aren’t; this code will print the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the previous two numbers in the series. The first two numbers are conventionally both 1.

However, let us make one small change in the program:

a, b = 0, 1
while a < 1000000:
a, b = b, a+b
print (a)

Now as you can see, the indentation of print(a) has been decreased, putting it in line with the while loop instead of its contents. This small change stands to completely change what out code does. In this new code, instead of printing all Fibonacci numbers up till a certain point, it will print only the first number of the Fibonacci sequence which is greater than the specified limit. This is because, instead of being printed at each execution of the loop, now this number will only execute once, at the end.

You may have noticed that we did not need to declare any of the variables before assigning values to them.

Numbers in Python

Python is very powerful at handling numbers. In the previous code sample for example, you would have to add considerably more zeros to 1000000 before you will actually notice the program taking time in performing the operation.

You can do simple mathematical operation with ease. Operations such as +, -, * and I work as expected. Like most other languages Python also includes the remainder or mod function %. However, Python in addition supports a '//' operation, which is an integer division operation. It will return the integer result for the operation while discarding the fraction. For example:

>>> 19/4
4.75
Normal division yields the expected outcome
>>> 19//4
4
Integer division discards the fraction (0.75)
flooring the result
>>> 19//-4
-5

With negative numbers the rounding works as expected for negative numbers, i.e. -4.75 rounds to -5
Another popular mathematical operation which is natively supported by Python is the exponent operator. You can use it as follows:

>>> 2**32
4294967296

Python supports multiple simultaneous assignments:

a = b c = d = 0
and
a, b, c, d = 1, 2, 3, 4

Python can very easily operate on complex numbers. This is very useful for those wanting to use Python for mathematical applications. You need not write your own class or use a library, complex operations are inbuilt. Hence they also have a much more natural syntax. Complex numbers are written as 1 + 5j or 29 – 34J. So the following will work out-of-the-box:

>>> (1+11J) + (9-13j)
(10-2j)
>>> (1+11J) - (9-13j)
(-8+24j)
>>> (1+11J) * (9-13j)
(152+86j)
>>> (1+11J) / (9-13j)
(-0.536+0.448j)

Many other complex number operations such as extracting the real part, the complex part, getting the magnitude, etc. are all supported. However let's move on.

Strings in Python

Strings in Python cannot be changed once assigned, unlike many other languages. So once you set a variable to a string value, you cannot manipulate the original string. As usual, you can express strings by enclosing them in double or single quotes. You can use quotes inside strings by using escaping the quotes (as in 'here's how to do it') or by using an alternate quote style (as in "here's how to do it"). If you have a multi-line string, you can use triple-quotes ('" or """) as:
‘’’
Here
is some
multi-line text
‘’’
Or you can use a raw string:
somestring = r"Here
is some
multi-line text”

In a raw string, escaped entities such as 'n' for newline "and ' are not converted but used as is.

String can be added:

Text = “Some” + “Text”
or even multiplied:
>>> text * 5
'SomeTextSomeTextSomeTextSomeTextSomeText'

Unlike some other languages, to find the length of a string in Python, you don't have something like string, length, instead you have to use the inbuilt length function as follows:

len(string)

This function (len) will also work on other objects such as arrays and hashes that have lengths.

Python has some very powerful ways of working with strings. Python includes a syntax for accessing the elements of a list or string using the usual box [], however in Python this syntax is greatly empowered. In Python, the square brackets take three parameters [start:end:step]. So somestring [a:b:c] is equivalent to saying "Return a string composed of the characters of string 'somestring' where every cth starting from index a and going on till index b is chosen." Some or all of these parameters can be omitted. If you omit a starting index, then it will be taken as 0, if you skip the end index, it will be taken as the length of the string, if you omit the step, it will be taken as 1. All three of these can be negative as well! In case of negative indices, the counting will start at the end of the string, as will become evident from the examples that follow. Finally, you can have a negative step as well, in which case characters will be read in reverse, making reversing s string in Python as simple as somestring[::-1].

Let us say we have:

Foo = “This is a sentence”

Then:

foo[2:11]
>>> ‘is is a s’
foo[:11]
>>> ‘This is a s’
foo[5:]
>>> ‘is s sentence’
foo[1:-1]
>>> ‘his is a sentenc’
foo[:-1]
>>> ‘This is a sentenc’
foo[::2]
‘Ti sansec’
foo[::3]
‘Tss nn’
foo[::-1]
‘ecnetnes a si sihT’

Lists in Python:

Lists are equivalent to arrays in many other languages. However in Python a list can have items of different types.

a_list = ['reticulatus', ‘molurus’, 2, 3.1]

Lists support the same kind of operations with square brackets as we have explored with strings above, with the same [start:stop:step] syntax.

To add elements to an existing list, you can use list.append(newitem), or listinsert(newitem,index). You can also extend a list with another list using list.extend(anotherlist). Removing items is accomplished with list.pop(), which removes the last item, or list.pop(index), which removes the item at the index position.

To search in a list, you can use listindex(value), or if you don't need to know the index, you can simply do the following:

>>> 3.1 in a list
True
>>> 2.7 in a list
False
>>> a_Iist.index{ 'molurus' )
1

Tuples in Python

Python also includes a very useful way of handling data called a tuple. A tuple is simply a comma separated sequence of data. A variable can be made a tuple as simply as:

a = 1, 2, 3, "four"

Quite similarly, you can get back these values in individual variables as:

x, y, z, w = a

Using tuple Python can accomplish stuff that is usually not found in other languages, such as the aforementioned multiple variable assignments in a single line, or returning multiple values from a function using the return statement.

Flow control:

In Python flow control is accomplished using the if, for and while statements. How they are used will become clear over the following examples:

The if statement:

if inp == "yes":
print{"You entered 'Yes' as your response.")
else inp == "no":
print{"You entered 'No' as your response.")
else:
print("Invalid response.")

The for statement:

The 'for' statement in Python differs from that of many other languages. Where you'd have something like:

for(i=0;i<11;i+=3)

In Python you'll have:

for i in range(0,11,3)

The range function can be used as range(start, end, step) to get the same outcome.

In Python the for statement can very easily be used to iterate over lists as follows:

for item in a list:
print (item)

The while function:

The while function has already been used by us before. It has a simple syntax:

while condition is true:
do ()
stuff ()

Defining functions in Python:

Python has a simple, consistent and easy to understand syntax for defining functions. The following is our previously used Fibonacci sequence code as a function:

def fibo{n) :
a, b = 0, 1
while b < n:
a, b = b, a+b
return a

Unlike many other languages, functions in Python con not only receive multiple arguments, but they can return multiple results as well! So if in our example above, we - for some strange reason - wanted to return both a and b, we could do that by simply returning them as:

return a, b

This utilizes a concept of Python called tuples, which we have mentioned before. The result could be retrieved as:

c = fibo (10)
d, e = fibo(100)

Where c will then be assigned the value of the tuple (8,13) , and c and d will respectively be assigned values of 89 and 144 respectively. An effective example would be a function returning coordinates (x, y) or (x, y, z).

Moving forward with Python

What we have covered here is just the bare minimum of Python, you have a great journey ahead, exploring this marvelous language and its libraries. However to give you a taste of what you can do in just a few minutes, here we will write a simple Python program to input a CSV file and output it as an HTML table:

import csv
def csv_to_html{csv_data):
table = "<table>"
for row in csv data:
table += "<tr>"
for column in row:
table += "<td>" + column + "</td>"
table += "</tr>"
table += "</table>"
return table
reader = csv.reader{open{"C:/ data.csv"))
html_output = "<html><head>"
html_output += "<title>csv table</title>"
html_output += "</head><body>"
html_output += csv to_html{reader)
html_output += "</body></html>"
print (html_output)

While this uses a lot of Python features which we haven't studied, you will notice that the code is still easy to understand. We have used import to import CSV functionality of the Python standard library. We have used the open function which can be used to open files. Our csv _to_html function reads each item of the CSV file and constructs a table from the data, which it returns as a string. Around that we will pad the standard minimum HTML code and print it.

Right now in this simple example we have hardcoded the file to open, and we are printing the output to screen instead of saving it to a file. With just a little more code, you can extend this program to open any file and output to any file by providing command-line parameters.

Currently you can test this file by running it as follows:

python csv2html.
py > htmlfile.html

Then open htmlfile.htm1; of course you will need to have a CSV file at 'C:data. csv' and it will need to be formatted in a standards-compliant way (saving from Excel might not work. use Google Docs).

Conclusion

Python is a great language to begin with, and requires little effort to get started. The wide abundance of libraries available for Python, from networking and GUI, to mathematics and data processing, make it simply to make application with a lot of functionality.

Learning Python won't go to waste, as it will always find a place in your workflow no matter which language you move on to.