1

I'm using Python 3.1.2 (Mac OS X 10.6) and found this weird behavior (I'm a newbie, btw):

On the interactive prompt:

>>> fraction = 4 / 3
>>> print(fraction)
1.33333333333
>>> print(type(fraction))
<class 'float'>

However, if I do the same thing in a script, results are different:

## fraction.py

fraction = 4 / 3
print(fraction)
print(type(fraction))

Output:

1
<class 'int'>

Is this normal?

2 Answers2

2

No it's not normal. Are you sure you are running Python 3 in that script? It's possible that Python 2.5 (the default install on Mac OS X) is chosen. Try to verify by

import sys
print (sys.version)

If you are running the script as ./fraction.py, you could force the shell to use Python 3.1 by putting

#!/usr/bin/env python3.1

in the first line.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • You're right. I'm using TextMate (a text editor) which has an automated mechanism for testing Python scripts and it's probably calling an older version (although in the output it reads 3.1.2). I double checked in the command line and you're right, there's something wrong with TextMate (not with Python). Thanks! – Andreas Fernandes Aug 09 '10 at 11:23
  • 1
    See http://stackoverflow.com/questions/1775954/using-python-3-1-with-textmate/ for how to use Python 3 with TextMate. – Ned Deily Aug 10 '10 at 02:50
1

What KennyTM said. The reason is that in Python <3, / signifies integer division if both arguments are integers. This was silly, and was changed in Py3k so that / always returns a float, even if dividing ints.

Katriel
  • 120,462
  • 19
  • 136
  • 170
  • I knew there was a difference, but forgot to double check if I was running the right version before posting the question. Thanks anyway! – Andreas Fernandes Aug 09 '10 at 11:52
  • @Andreas Fernandes If you need the 3.0 behavior in 2.x, put `from __future__ import division` as the first line in your script – Nick T Aug 09 '10 at 16:56