My Technical Blog
Archive for October, 2008
I'm Learning Python (part 5)
Oct 29th
I’m Learning Python (part 5)

String Is Immutable?
Last time I told you to try to change a specified character, you must have failed if you tried:
>>> s[0] = ‘c’
The error you’d get is:
TypeError: ‘str’ object does not support item assignment
This means that strings are immutable, so are core-types, numbers and tuples, they can’t be changed, while lists and dictionaries can be changed freely.
More Methods?
All the previous methods and operations are sequence operations, but strings have more methods:
>>> s = ‘My Text’
>>> s.find(‘Tex’ ) #returns the index of the first occurrence of the parameter
3
>>> s.find(‘abc’ ) #if the parameter wasn’t found it will return -1
-1
>>> s.replace(‘Text’, ‘Code’ ) #replaces every occurrence of the first parameter with the second one ‘My Code’ >>> s #notice that the string hasn’t changed
‘My Text’
>>> s = ‘aa,bb,cc,dd’
>>> s.split(‘,’ ) #splits the string into a list of values separated with the parameter
['aa', 'bb', 'cc', 'dd']
>>> s =’My Text\n’
>>> s.rstrip() #removes white space characters from the right of the string
‘My Text’
>>> s #don’t forget that the string hasn’t changed ![]()
‘My Text\n’
>>> len(s) #returns the length of the string
8
>>> ord(‘\n’ ) #returns the ASCII code for the given character
10
>>> s = ‘MyTextA’ # is the null character though it doesn’t terminate the string ?
>>> len(s)
9
>>> s
‘MyTextA’
Wanna Get More?
Of course I can’t talk about every method for every type, but I’ll give you a simple way to get more, in Python there is a method called “dir” which lists the object’s methods and properties:
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', __ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', __hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', __reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', __sizeof__', __str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', isalnum', isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper','join', 'ljust', 'lower', 'lstrip', 'partition', replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Don’t care about those who has underscores, but the rest are methods.
Now to know more about a specified method you can use the “help” method:
>>> help(s.count)
Help on built-in function count:
count(…)
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in string S[start:end].
Optional arguments start and end are interpreted as in slice notation.
What About Regular Expressions?
Users with a background about regular expressions will definitely ask about it, and the answer is yes you can use them with strings:
>>> import re
>>> match = re.match(‘Hello[ \t]*(.*)world’, ‘Hello Python world’ )
>>> match.group(1)
‘Python’
>>> match = re.match(‘/(.*)/(.*)/(.*)/’, ‘/usr/lib/bin/’ )
>>> match.groups()
(‘usr’, ‘lib’, ‘bin’ )
Of course you can do more as you know with regular expressions like replacing and splitting, try “dir” and “help” for more
What Is The Difference Between ‘Text’ And “Text”?
There is no difference at all, but there is a third way to write strings:
>>> s = “”"Text”"”
This way preserves the text formatting, which means you can write:
>>> s = “”"
<html>
<head></head>
<body>
<b>’I Love “Python”‘</b>
</body>
</html>
“”"
>>> s
‘\n<html>\n<head></head>\n<body>\n<b>’I Love “Python”‘</b>\n</body>\n</html>\n’
You can use this way to write pre-formatted text just like XML and HTML.
Lists And Sequences:
Lists are sequences like strings and they support every thing we talked about when discussed strings methods but the difference is that the results of methods are lists instead of strings, and that lists are changeable objects which means they support changing in place:
>>> L = [123, 'mpcabd', 1.23] #lists support multi-types ![]()
>>> len(L)
3
>>> L[0]
123
>>> L[-1]
1.23
>>> L[:-1]
[123, 'mpcabd']
>>> L + [4, 5, 6]
[123, 'mpcabd', 1.23, 4, 5, 6]
>>> L
[123, 'mpcabd', 1.23]
Lists are so much like arrays but they have no fixed size, so you can append to them and delete from them:
>>> L.append(111)
>>> L
[123, 'mpcabd', 1.23, 111]
>>> L.pop(0)
['mpcabd, 1.23, 111]
You can even sort and reverse them:
>>> L = ['a', 'z', 'c']
>>> L.sort()
>>> L
['a', 'c', 'z']
>>> L.reverse()
['z', 'c', 'a']
To find more try “dir” and “help”
What abound boundaries?
Try the following and you’d see an error:
>>> L = ['a', 'b', 'c']
>>> L[9]
IndexError: list index out of range
This means that Python checks for boundaries not like C and C++.
Can I Nest Lists?
Yes ![]()
>>> M = [
[ 1, 2, 3 ], [ 4, 5, 6 ],
[ 7, 8, 9 ] ]
>>> M
[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
>>> M[1] [4, 5, 6]
>>> M[1][2]
6
This is a good way to define matrices, but I advise you to use NumPy for mathematical operations, ‘cuz it is optimized for fast use.
What Are List Comprehensions?
Python includes along with what we’ve discussed a powerful methods called “List Comprehension Expressions”, suppose we wanna extract the second column of our previous matrix (M), what would you do? Python provides a good way:
>>> col2 = [row[1] for row in M]
>>> col2
[2, 5, 8]
Not good enough? Take this:
>>> [row[1] + 1 for row in M]
[3, 6, 9]
>>> [row[1] for row in M if row[1] % 2 == 0]
[2, 8]
Not enough yet? Take this one and take a nap ![]()
>>> [M[i][i] for i in [0, 1, 2]]
[1, 5, 9]
Not enough? I’ll kill you then ![]()
For more wait for me to study
Bottom Line:
I’m sorry I was late this time but I’m really having a busy phase @ work, please wait for more and don’t get bored.
Cheers.
I'm Learning Python part 4
Oct 15th
I’m Learning Python (part 4)

Why Use Built-In Types?
Most of the time in programming you’ll use lists, stacks, arrays, queues and dictionaries, so instead of constructing them, Python gives you a bunch of built-in types to use. The built-in types implement the semantic of the type ADT (Abstract Data Type), and they are fast, ‘cuz some of them are written in C and C++.
What Core Data Types Does Python Provide?
As in any language, Python provides the usual list of types besides other data types:
- Numbers: 1234, 3.1415, 999L, 3+4j, Decimal
- String: ‘Some text’, “a Text”
- Lists: [1, [2, 'Three'], 4]
- Dictionaries: {‘food’ : ‘Lemon’, ‘taste’ : ‘Yummy!’ }
- Tuples: (1, ‘Name’, 5, ‘u’ )
- Files: myFile = open(‘someFile’, ‘r’ )
- Other Types: Sets, Types, Boolean, Object, None
And don’t forget that everything is an object at the end ![]()
Although Python has no variable declaration – you just assign the value to a variable name and it will be declared automatically -, it keeps track of your variables dynamically, so when you assign a string value to a variable you can use string operations only on it, and so on.
Now let’s discuss the types in a glance ‘cuz we’ll talk about them in depth later.
Numbers:
Python provides: integers (1234), floating point (3.1415), unlimited precision long (43251278364218357642386321984621734982137469321856412L), complex numbers (4568 + 789j), fixed precision decimals and sets.
Python also provides the simple operations:
+ is used for addition, – for subtraction, * for multiplication, ** for exponents, / for division.
You can calculate whatever you want (2 ** 1000000, but you don’t wanna print 300000 digit
).
When printing numbers there are two methods of printing, the first one is called ‘repr’ (object as code) and it prints the number with full precision, the second one is called ‘str’ which prints the number in a user-friendly way:
>>> 3.1415000000000002 * 2 #repr
6.2830000000000004
>>> print 3.1415000000000002 * 2 #str
6.283
We’ll discuss this method later when we introduce classes ![]()
Besides basic operations Python provides a module called ‘math’ which has useful methods and variables:
>>> import math
>>> math.pi
3.1415926535897931
>>> math.sqrt(123)
11.090536506409418
And it also provides a module called ‘random’ which generates random numbers:
>>> import random
>>> random.random()
0.8591504308650737 #You might get another value
>>> random.choice([1, 2, 3, 4])
4 #You might also get another value
We’ll discuss more numbers types soon, but now let’s move to another type.
Strings:
Strings as you might all now are arrays of characters (in Python we call the array a sequence).
Some of the sequence operations:
>>> s = ‘My Text’
>>> len(s)
7
>>> s[0]
‘M’
>>> s[3]
‘T’
A good indexing way is the negative indexing, which starts from left to right:
>>> s[-1] #Equivalent to s[len(s) – 1]
‘t’
>>> s[-2] #Equivalent to s[len(s) – 2]
‘x’
Slicing is another way of indexing in sequences, and it is used to extract a portion of the sequence:
>>> s[3:6] #A slice starts from 3 and ends at 5 not 6
‘Tex’
In slicing the left parameter’s default value is 0, and the right’s is the length of the sequence, which leads to some other slicing operations:
>>> s[:]
‘My Text’
>>> s[1:]
‘y Text’
>>> s[1:len(s)] #Same as s[1:]
‘y Text’
>>> s #Notice that s hasn’t changed, we were given new objects.
‘My Text’
>>>s[:-1] #Everything but the last character ![]()
‘My Tex’
As you have noticed we were given new objects, which leads to the fact that slicing using [:] will copy the sequence into another new sequence, which is a great way to copy lists and other sequences.
As sequences, strings support concatenation and repetition:
>>> s + ‘ Is Beautiful’
‘My Text Is Beautiful’
>>> s #s hasn’t changed
‘My Text’
>>> s * 5
‘ My TextMy TextMy TextMy TextMy Text’
You see, + is used here for concatenation while in numbers it is used for addition, this is called operator overloading in other languages.
Bottom Line:
We’ll continue talking about types next time, until then create numbers and strings. Try to set a value to specified index of a string, what would you get?
Cheers.
I'm Learning Python part 3
Oct 11th
I'm Learning Python (part 3)
What Is Interactive Mode?
When you install Python on your platform you'll find an executable called 'python', when you run it you'll find a terminal and you'll see something like the following:
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
This is called interactive coding (or interactive mode), here you can write Python statements and the interpreter will execute them directly, let's try:
>>> print "I Love Python"
I Love Python
>>> print 2 ** 10
1024
>>>
You can write any statement here (even those who are more than on line as we'll see later).
If you remember we said that the Python compiler and interpreter are always in present at runtime, so that's why you can execute the statements directly here. Another benefit you get from the presence of the compiler and interpreter at runtime that you can let your program execute Python code written by the user, and that's what some programs do, they let the user manipulate the program's behavior by writing his/her code inside the program.
To do so you can run the "exec" statement like this:
>>> exec "print \"I Love Python\""
I Love Python
>>>
Here we invoked a method called "exec" and it takes a string parameter, this string contains Python code, and the interpreter will run it, so you can simply read code from the user and run it for him/her. This method is available anywhere (not just in the interactive mode).
You must have noticed using the escape character \" in the text, and that is to tell the interpreter that this is not the end of the string and it is a double quotation inside the string, there are more escape characters that we'll find more in the upcoming parts.
Another feature to talk about in the interactive mode that you don't have to write print every time, so the next statement will run without errors:
>>> "I Love Python"
'I Love Python'
>>>
But beware, you must use print in any other mode, interactive mode is the only mode which doesn’t need the print statement, that's 'cuz it is made to print the results.
You might ask, what about statements that don't return values, what would the interactive mode print for them? The answer is: simply nothing
>>> text = "I Love Python"
>>>
The previous statement is an assignment statement, which declares a string called "text" and has the value of "I Love Python".
To exit the interactive code you use the break character (Ctrl+Z in Windows, Ctrl+D in Linux) and hit return.
What Are Modules?
Let's here explain the Python program hierarchy:
Each program consists of modules -> Each module consists of statements -> Each statement consists of expressions -> Each expression creates and processes objects -> Objects are the raw materials you'll use
When you write a Python program you write it in files, these files usually called modules, the module is a namespace, so each module has its own variables and methods. You can have two variables with the same name, but you must put each one in a module.
We'll use modules (for now) to run our code multiple times without the need of re-typing it again.
You can access another module using "import" statement, so let's try something:
- Open your editor and write the following in it:
text = "I Love Python"
print text - Save the file somewhere with the name "module1.py"
- Now start a new file and write the following in it:
import module1
module1.text = "You Know I Love Python"
print module1.text - Save the file in the same folder which has "module1.py" with the name "module2.py"
- Now let the Python interpreter run your module2 file:
python [SOME FOLDER]/module2.py - You must see the following:
I Love Python
You Know I Love Python
What happened here? In module2 I only printed the variable after editing it, why was it printed before it was edited?
When you import a module, you're simply running it, so the Python interpreter ran module1, and executed the print statement so you see "I Love Python", then it executed module2, it edited the value of the variable in module1, then executed the print statement in module2, and you see "You Know I Love Python".
So importing means running, but what if I needed to run the code again? Knowing that you can't import a module more than one, what should we do?
There is another statement "reload" which is a method and takes a string with the name of the module to re-run it again, but it should be imported before.
Try adding this line to your code in module2.py:
reload(module1)
Re-run your module2 and you must see:
I Love Python
You Know I Love Python
I Love Python
The third line is actually the print statement in module1 file.
What Is The Difference Between "import [MODULE]" And "from [MODULE] import"?
The first – import [MODULE] – imports and runs the module, but when you want to access its variables you should write: [MODULE].[VARIABLE], so each time you want to use the variable you should write the module's name followed by a period before the variable's name.
The second – from [MODULE] import – imports the specified variables from the module, so to import the "text" variable from "module1" in the previous example you write:
from module1 import text
To import more than one variable separate them with columns:
from [MODULE] impor [VAR1], [VAR2], …, [VARN]
Notice that importing a variable lets you use the variable without the need to write the module's name before it, you can simply use the "text" variable in module2 after importing it without writing module1.text.
Beware that importing a variable that has the same name of a local variable will replace the local one, for instance:
in module1.py write:
text = "I Love Python"
in module2.py write:
text = "You Know I Love Python"
from module1 import text
print text
Executing module2 will give you: I Love Python.
How can I write hints and comments in Python?
Using the sharp – # – character will hint the following text until the end of the line:
text = "I Love Python" #a declaration of a variable named text
Bottom Line:
Next time we'll learn about built-in types in Python, till then try to create and import and print modules and variables, try that in both files and interactive mode, try to make syntax errors, try to divide by zero.
Cheers.
I’m Learning Python part 2
Oct 7th

Who Uses Python?
In the world there are more than 1 million Python user, that’s because it’s
open source, and because it is implemented for every platform, and it comes
included within Linux distributions and Macintosh computers and more.
- Google uses Python in its web search system, and it employs the Python’s
creator. - YouTube is largely written in Python.
- BitTorrent file sharing system is a Python program.
- Intel, Cisco, HP, Seagate, Qualcomm and IB< use Python for hardware
testing. - Industrial Light & Magic, Pixar, and others use Python in the production
of movie animation. - NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific
programming. - iRobot uses Python to develop commercial robotic vacuum cleaners
- NSA uses Python for cryptography and intelligence analysis.
See Python website for more.
How Does Python work?
Python is not compiled (almost), it is interpreted. So when you run the program
the interpreter will run it line by line without compilation.
You might say “Why did you say almost?”, the answer is, Python as described
before can be compiled into byte code, so it’ll be faster for the interpreter
to execute it than the source code, just like Java’s byte code and .NET’s MSIL.
Python files have a .py extension normally, so when you write Python code you
should save it with a .py extension.
Let’s try and write our first Hello World Python program:
- Open the editor you use (Emacs, Notepad, Notepad++, …).
- Write this line inside it:
- print “Hello World, It’s My First Python Program”
- Save the file as .py file.
- Now you should tell the Python interpreter to run your file, depending
on your platform you should have the Python interpreter in (“C:\Python[VER]\”
in Windows where [VER] is the version of the Python release you have [24,
25, 26,…]) or in (“/usr/bin/” in Linux). - In Windows open a command prompt and guide it to the location of your
Python. - In Linux open a terminal and go to the location of your Python interpreter.
- Now you can execute the following command on both platforms:python [FILE]
Where [File] is the location of your .py file.
- Now you should see some thing like this:python [FILE]
Hello World, It’s My First Python Program
Very easy, right?
Although it is not that big program but you can run your files this way
.
Now let’s understand what happened:
The Python interpreter was given a file to run.
If it has write privileges it’ll compile it into byte code and you’ll see that
a new file was created next to your file with a .pyc extension, if it doesn’t
it’ll run it as source code.
It reads the first line (which is a print statement) and runs it and you see
the result, the execution takes place inside the PVM – Python Virtual Machine,
which handles the execution of Python byte code and source code to run on more
than one platform without change in code.

If you have a background in C or C++ you might find a change in the way of running
and compiling code, ‘cuz there is no making and linking in Python, and it is
not compiled into machine code (binary file), instead it runs inside a virtual
machine, that’s why some Python code will run faster in C++ and C.
But don’t be afraid, 90% of the time you’ll be running your programs as if they
were written in C or C++, there won’t be any difference in the time of execution,
and that’s because of the Python simplicity which makes the program in Python
shorter and simpler than C or C++, and because it’s optimization which we’ll
describe later.
In Python you’ll notice that the compiler and the execution environment are
one thing, the compiler always present in runtime, and that leads to rapid development
cycle, with no linking and making stage.
CPython runs inside the PVM, while Jython runs inside the JVM and IronPython
.NET runs inside .NET Framework or Mono.
Jython and IronPython .NET allows the Python program to use Java and .NET classes
respectively.
If you don’t wanna use Java or .NET classes you should use CPython, ‘cuz it’s
faster and the most complete, CPython runs like C and C++ so it is the fastest.
In Jython the Python byte code is translated into Java byte code to be run inside
the JVM, while in .NET it is translated to MSIL.
What Are The Frozen Binaries?
Python has something called Frozen Binaries, which are the executables, if you
chose to create a frozen binary for your program, you’d end up with an executable
that runs on a specified platform (exe for Windows).
This executable has a great feature; it includes your program along with its
dependencies and the Python interpreter. Yes you don’t have to tell the user
to install a Python interpreter to be able to use your program, he/she doesn’t
have to know that your program is a Python program.
You can use Py2Exe to get an exe of your program (Which runs only in Windows),
or PyInstaller which gives you the ability to create a frozen binary for Windows,
Linux or UNIX. And you can use Freeze the original one. Those are available
free of charge, you can check Python website or Vaults of Parnassus (http://www.vex.net/parnassus).
What IDE’s To Use With Python?
Python comes with a simple IDE called IDLE you can use it, or you can use Emacs, but IMHO
Eclipse with PyDev make a great IDE for you and Python.
Bottom Line:
Today it was just a description on how Python runs your program, and we wrote
our Hello World program.
For the next part, try to use the ** operator – which is the power operator
in Python – to see how much you can do in Python, e.g.:
print 2 ** 10
1024
Try huge numbers and see
Cheers.
I'm Learning Python part 1
Oct 4th

I’ll start posting this series of blogs on WordPress and CSC, here I’ll write what I’m gonna learn on my way to learning Python.
If you don’t know what Python is, or you’ve heard about it but you’re not sure what it is, my first blog will cover it for you.
What is Python?
Python is a programming language, this programming language was created in 1990, this programming language has proved its power through the last 18 years she’s been with us.
Why should I be interested in learning a new language?
The most points that will catch your interest in this language are:
- It’s Object Oriented:
Python supports classes, inheritance, multiple inheritance, polymorphism, operator overloading and more.
Python is OOP from ground up, besides it’s like C++ supports both object oriented and procedural programming, so it may be used for scripting applications.
- It’s Free:
Python is completely free to use and redistribute, it is also widely supported through web portals where millions of users world-wide can help you find solutions for your problems.
- It’s Portable:
Python first was written in C, and because of that it can be run on almost every platform, you can run it on (Windows, Linux, Mac OS, BeOS, PDAs, Cell Phones, Gaming Consoles, …).
Everything is portable, that’s because Python code is compiled into byte-code (Like .NET and Java), and so it can be run on any platform with a Python interpreter.
- It’s Powerful:
Python sits on the chair along with Perl, Tcl and Scheme as a powerful scripting language, while also it sits on the chair with Java and .NET as a powerful Pure OOP language, and of course it shares the chair with C and C++ as a powerful programming language that is capable of doing everything.
While sitting on more than one chair at the same time, Python provides the simplicity in writing a fully readable code.
From its most powerful features I’ll write some and I’ll explain them deeply when I understand them
- Dynamic Typing.
- Automatic Memory Management:
This one I already know from .NET, Python has its own garbage collector which runs automatically and deallocates space from unused objects in the memory. - Programming for large systems using OOP allows you to develop components and systems so you can reuse them in most of your applications.
- Built-in tools used for manipulating built-in types such as lists and collections.
- Libraries from regular expressions to networking, all libraries can be used easily.
- Third-party utilities: since Python is open source developers from around the globe can build their tools and libraries and everybody can use them.
- It’s Mixable:
You can use Python and call your programs and methods from inside C and C++ and even Java and .NET, you can also call C and C++ methods and tools from Python along with Java and .NET.
- It’s easy to use and learn:
You’ll notice just like I have that Python is an easy yet powerful language which can be used in every technical field without losing it simplicity.
What can I do with Python?
Here I’ll tell you what fields you can use Python in, but in a glance ‘cuz I don’t know how to use it yet.
- System Programming:
Because it can be used as scripting language, Python can be used to develop shell tools, which can communicate with system shell and provide a layer for you to search files and folders, launch applications and even do parallel processing using processes and threads.
- GUIs:
Using Tk GUI, Qt, GTK, MFC and Swing you can make your application have a GUI, but not any GUI, your GUI is cross-platform and you’d be able to run your application on any platform.
- Internet Scripting:
You can develop web applications using Python, you can do Server scripting, Server-Client Scripting and Client Scripting.
A lot of websites already use Python now.
You can use FTP to transfer files, parse XML files, parse HTML and you can generate HTML based on Python code.
- Gluing:
Python can be glued to C, C++, .NET and Java applications.
Python now has 3 major implementations: CPython which is the base implementation, Jython which can be run inside the JVM (Java Virtual Machine), and IronPython .NET which can be run inside .NET Framework.
- Database Applications:
Python can use Sybase, Oracle, Informix, ODBC, MySql, PostgreSQL, SQLite and more.
Python even has a built in database API which can be used with any database system, you can easily change it from anyone to anyone by just switching the used interface.
- Numeric and Scientific Programming:
Python can be used easily to create scientific applications, there is an extension called NumPy which can do more than Matlab!
You can calculate 22000 in milliseconds:
114813069527425452423283320117768198402231770208869
520047764273682576626139237031385665948631650626991
844596463898746277344711896086305533142593135616665
318539129989145312280000688779148240044871428926990
063486244781615463646388363947317026040466353970904
996558162398808944629605623311649536164221970332681
344168908984458505602379484807914058900934776500429
002716706625830522008132236281291761267883317206598
995396418127021779858404042159853183251540889433902
091920554957783589672039160081957216630582755380425
583726015528348786419432054508915275783882625175435
528800822842770817965453762184851149029376.
You don’t have to wait to get this value
- More:
Python can be used in more fields, XML, Gaming, Graphics, Robots, Networking and more, everything is possible
Bottom Line:
That’s enough for today, hope I’ll tell you more on my next blog.
For now I’d suggest you to read more about the language and its features from the language website: www.Python.org.
And also don’t forget to download the appropriate built for your platform.
Cheers.






