Monday, February 8, 2010

Arithmetic operation involving only integers do not always return an integer

int/int

Unlike C, in Python arithmetic operation involving only integers do not always return an integer. If you want a truncated integer returned from a integer division, use // instead of /.

Lets see the examples:
a = 3;
b = 1;
x = a/b;
print(type(a), " / ", type(b), " produce ", type(x));

a = 3.0;
b = 1.0;
x = a/b;
print(type(a), " / ", type(b), " produce ", type(x));

a = 3;
b = 1;
x = a//b;
print(type(a), " // ", type(b), " produce ", type(x));

a = 3.0;
b = 1.0;
x = a//b;
print(type(a), " // ", type(b), " produce ", type(x));






Indentation and block

Indentation and block

Unlike most other programming language such as c, java, in which using braces to define block; Python use whitespace and indentation to define block structure.

Example 1:
x = 0;
while(x < 10):
x += 1;
y = x;
print("x = ", x);
print("y = ", y);




Example 2:
x = 0;
while(x < 10):
x += 1;
y = x;
print("x = ", x);
print("y = ", y);




IDLE, the default IDE of Python, automatically indents lines for you.