Abd Allah Diab's Blog
My Technical Blog
My Technical Blog
Dec 19th
I’m sorry to announce that I won’t be able to post any posts until the end of January 2009, and that’s because of my university exams
Thank you for visiting me, and see ya soon
P.S.
Wish me luck and high marks
Nov 29th

First of all I wanna apologize for being late with this part, I’ve had busy days first during Shaam 2008 expo and second during some studies at the college and last busy time past launching Bawabaty project.
Numbers in Python are divided into 5 sections:
Integers:
Such as: 1234, -1234, 0
Long Integers (unlimited size):
Such as: 71632487932648921735413278645238947231659821365213847L
These numbers grow as long as your memory can hold, and it ends with a small or capital L but it is an optional literal, you can define:
/>>> TheLongVariable = 99999999999999999999999999
/>>> TheLongVariable
99999999999999999999999999L
Floating Point Numbers:
Such as: 1.234, 3.14e-10, 4.01e+12
You can define them using points, e or E.
Octal and hex literals:
Such as: 0172, 0x9fab, 0X3FBC
Octal is defined by starting your number with a leading zero, while hexadecimal is defined by starting you number by a leading 0x or 0X.
Complex Numbers:
Such as: 3+4j, 3.0-5.1j, 3J
Complex numbers are defined by a j or J at the end of the number, the number can consist of two parts, real and imaginary, so all the following are complex numbers:
1 + 3j, 3j, 5J, -10.1j
Of course you can use +, -, *, /, <, >, ==, !=, <> as any other programming language, but Python has more:
**: Power, 2 ** 3 is 8.
//: Is truncated division, 5 // 2 is 2
%: Remainder, 5 % 2 is 1
You can use also bitwise operations:
/>>, << shift right and left, 5 << 2 is 20, 24 >> 3 is 3.
|, & Or and And, 4 | 3 is 7, 7 & 2 is 2.
Just as any other programming language, Python deals with expressions using operator precedence: 3 + 4 * 2 is 11 because * is done before +.
Of course you can use parentheses to define the way you want to deal with the expression, (3+ 4) * 2 is 14.
When mixing multiple types in an expressions, all types are converted up, 40 + 3.14 will be calculated as 40.0 + 3.14. The types are ordered like this:
Integers < Long Integers < Floating Points < Complex Numbers.
The type of the result of a mixed expression is the type of the higher type, so 40 + 3.14 is a floating point, but you can force it into an integer using: int(40 + 3.14).
During our trip in Python till now we used variables but we haven’t talked about them:
Variables are created once they are assigned a value.
Variables are replaced with their values in expressions.
You can’t use an unassigned variable, because simply you don’t have the variable yet.
Variables are references to objects.
Try this
/>>> a = 3
/>>> b = 4
/>>> b / (2.0 + a)
0.80000000000000004
/>>> print b / (2.0 + a)
0.8
We’ve seen something like this before, and we discussed it, the difference between the two methods is that each one uses a specified function, the first uses a function called repr which prints the value as it is in your memory, while the other uses a function called str which prints the value in a user friendly way.
Python provides functions for Octal and Hex conversion:
/>>> oct(64)
’0100′
/>>> oct(8 )
’010′
/>>> hex(255)
’0xff’
And vice versa, Python provides functions for retrieving integers out of Hex and Oct:
/>>> int(’0234′)
234
/>>> int(’0234′, 8 )
256
/>>> int(’0234′, 16)
564
And it also provides a way to format numbers in strings, which we will cover in another part, but a small example won’t hurt:
/>>> “%o %x” % (25, 21)
’31 15′
Other built-in functions and methods are in math module, which you can import and use:
/>>> import math
/>>> math.pi, math.e
(3.1415926535897931, 2.7182818284590451)
/>>> math.sin(math.pi / 2)
1.0
The result shown in parentheses is a tuple (which we covered last part), it is shown in a tuple because we put a column between math.pi and math.e
Thank you for waiting for this part, and until I meet you on another part try to read more about numbers from the online documentation of Python.
Cheers.
Nov 8th

Oct 29th

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.
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’
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.
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
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 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”
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++.
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.
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
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.
Oct 15th

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++.
As in any language, Python provides the usual list of types besides other data types:
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.
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 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.
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.