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));