1. 程式人生 > >Python運算子中/和//的區別

Python運算子中/和//的區別

首先先看單斜杆的用法:舉幾個栗子:

>>> print 5/3,type(5/3)

1 <type 'int'>
>>> print 5.0/3,type(5.0/3)
1.66666666667 <type 'float'>
>>> print 5/3.0,type(5/3.0)
1.66666666667 <type 'float'>
>>> print 5.0/3.0,type(5.0/3.0)
1.66666666667 <type 'float'>

可以看出,在A/B的返回型別取決與A和B的資料型別,只有A和B都為int型時結果才是int(此時表示兩數正除取商),其他情況全是float型,在看看數值,當結果為float型時,結果是保留若干位的小數,是我們正常思維中的除法運算

在看看雙斜杆的栗子:

>>> print 5//3,type(5//3)
1 <type 'int'>
>>> print 5.0//3,type(5.0//3)
1.0 <type 'float'>
>>> print 5//3.0,type(5//3.0)
1.0 <type 'float'>
>>> print 5.0//3.0,type(5.0//3.0)
1.0 <type 'float'>
>>> 

在A//B中的返回型別與A/B的時一樣的,但//取的是結果的最小整數,而/取得是實際的除法結果,這就是二者的主要區別啦