My Technical Blog
Posts tagged Tutorial
I'm Learning Python part 10 (last one)
Sep 16th
I'm Learning Python part 10
(last one)
Back to blogging
As usual, I will apologize for not blogging for a long time.
I have been very busy, university exams, university projects, job projects, teaching and learning.
Python Course
At Damascus University, in the faculty of informatics we managed to create free courses to students, and I was one of the teachers there, I taught Python to students.
As far as I know this course was the first Python course in Damascus University.
Even though the students were a few (actually a very little few about 8 ~ 10 students) the course was great. We managed to learn Python 2.6 Syntax, a little bit of its standard library and a little bit of PyQt4 in about 7 days x 2 hours daily.
As far as I know too, students understood it and found it great, and I hope they’ll be using this great language more in their programs.
Why last one?
The tour with Python ends here, while it ends here it starts here too, it ends here because so far you’ve learned what you need to start your own path in Python. And it starts here because you’re fully equipped with the base tool to discover more tools, I’ll let you discover the standard library and 3rd-party libraries on your own, because everyone differs in his/her interests.
I’ll be blogging more on more technical issues but they might not be I’m Learning Python series
.
Let’s stop talking here and move directly to the heart of our last lesson.
More >
I'm Learning Python part 9
Mar 20th
I’m Learning Python part 9

Classes In Python
Defining a Class
Classes in Python are defined like this:
I'm Learning Python part 8
Feb 21st
I’m Learning Python part 8

Python 3.0
Since the last time I wrote an article Python many changes happened in my life, one of them is the release of Python 3.0 (Which is known also as Python3K and Python3000).
Python 3.0 is the first intentionally backwards incompatible Python release, which means that there are some changes you must notice before start coding in Python 3.0.
Don’t worry that much, the language has become more useful, and also there is 2to3 source-to-source conversion tool which converts your Python 2.x code to meet the requirements of Python 3.0
To find more about change in Python please refer to Python website.
P.S.
From now on all the code will be written in Python 3.0.
Decimal vs. float
Please try the following code in your python console:
d = 0.1You’d get this output:
print(d)
print(str(d))
0.1
Strange ain’t it?
The second value is the one you put in the variable.
The first one is the real value represented in memory. This is not Python’s fault, this happens because of the way computer store float values in memory as 0′s and 1′s, computers use floating point IEEE-745 representation.
Using this representation unfortunately we can’t represent any float value using 0′s and 1′s, and 0.1 is one of those poor values (The reason is that it can’t be represented in sum of powers of 0.5).
So what all programming languages do is that they ignore the small fraction so it would be 0.1 instead of 0.10000000000000001, but Python doesn’t.
Try this code in Java if you have:
public class NoDifference{You’d get this output:
public static void main(String[] args){
double a = 0.1;
System.out.println(a);
a = 0.10000000000000001;
System.out.println(a);
}
}
0.1
So Java doesn’t differ those two values while they’re different. (Such a difference could make a disaster in a nuclear reactor
)
If you want to go with the flow and ignore this difference in your calculations you’d have to use another data type than float, you’ll have to use Decimal.
from decimal import Decimal
d = Decimal("0.1")
print(d)
0.1
Decimal data type allows you to represent any decimal value you want
It also supports addition, subtraction, multiplication, division and modulo, but the two sides must be Decimals.
Functions
Let’s write a function that prints Fibonacci series to a given boundary:
def fib(n):1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
"""Prints Fibonacci series up to n"""
a, b = 0, 1
while b < n:
print(b, end = " ")
a, b = b, a + b
#Now we can call the function by its name
fib(2000)
Now let’s describe what we have done:
- def is a keyword in Python, def defines
it defines methods and classes. - fib is the method’s name, method’s name must meet the same requirements for variable’s name. (first character a-z, A-Z or _, other characters a-z, A-Z, 0-9, _)
- (n) is the list of parameters, notice that no type names in this list. parameters are comma separated.
- : defines the scope of the method. All statements under this scope must be tab-aligned.
- “”"Prints …”"” is an optional string literal that describes what this method does, it will help you and other developers understand the purpose of the method, and it will also help you auto-generate documentation for your code.
- a, b = 0, 1. define two variables and give them two values. a handy way
- a, b = b, a + b. also assign two values to two variables.
The previous code defines a procedure (not a function) because it doesn’t return a value, let’s modify the code so it builds an array of Fibonacci values instead of printing them:
def fib(n):[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
"""Prints Fibonacci series up to n"""
a, b = 0, 1
result = []
while b < n:
result.append(b)
a, b = b, a + b
return result
f = fib(100)
print(f)
What we have added is the return statement only, which returns a value to the caller.
One more thing to be told is default arguments:
def askYesNoQuestion(question, retries = 4, complaint = "Please write Yes or No only!"):Default arguments are assigned a default value if they aren’t when called.
while retries > 0:
answer = raw_input(question)
if answer in ['y', 'ye', 'yes', 'yep']: return True
if answer in ['n', 'no', 'nop']: return False
retries -= 1
print(complaint)
raise IOError, "stupid user"
#Now we can call it
askYesNoQuestion("Are you sure?", 1, "What?!")
askYesNoQuestion("Overwrite?", 1)
#Same as askYesNoQuestion("Overwrite?", 1, "Please write Yes or No only!")
askYesNoQuestion("Do you know me?")
#Same as askYesNoQuestion("Do you know me?", 4, "Please write Yes or No only!")
askYesNoQuestion("Do you have a pen?", complaint = "You can say no if you want!")
#Same as askYesNoQuestion("Do you have a pen?", 4, "You can say no if you want!")
You can set arguments values when calling by writing Name = Value.
Default parameters can’t be followed by non-default arguments.
Important note:
Default arguments are evaluated only once, so the following code will accumulate the values:
def f(a, L = []):[1]
L.append(a)
return L
f(1)
print(f)
f(2)[1, 2]
print(f)
f(3)[1, 2, 3]
print(f)
If you don’t want the function to behave like this you can write:
def f(a, L = None):Let’s explain what I meant by saying “are evaluated only once”:
if L is None:
L = []
L.append(a)
return L
When the Python interpreter reaches the line that defines the method, it allocates a list in the memory and assigns its address to L the reference.
Next time you call the function L will reference the same list it referenced the time it was created in memory, so it will always reference the same object.
The second code actually referenced to None, so every time you call the function it will assign None to L.
By understanding what I meant you can consider the following example:
i = 1012
def f(a, b = i):
return a + b
i = 11
print(f(2)) #Will it print 12 or 13?
That’s because b was given the value of i before the interpreter reached the line in which i was give the value of 11.
Bottom Line
Not that much I presented in this part, but you should consider upgrading your Python knowledge to Python 3.0 for the next time.
And by the way, I’m sorry, I’ve betrayed you and learned a lot during the last month, I have also started creating GUI Applications using Python and Qt, so please forgive me ![]()
Cheers.
I'm Learning Python part 7
Nov 29th
I’m Learning Python (part 7)

Apology:
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:
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
Python has lots of built-in numeric tools:
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).
Variables:
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.
repr & str:
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.
More Functions:
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
Bottom Line:
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.
I'm Learning Python part 6
Nov 8th
I’m Learning Python (part 6)

Dictionaries
To sort a dictionary you should sort its keys and then print the values of the keys after sorting like the following:
Nesting
Memory issue
Missing keys
To avoid this mistake you can ask the dictionary if it has the key then you can access it:
.






