Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Division in Pythonista App
-
I am new to programming and using the pythonista app altogether. When I type:
x=5/2
print(x)The console on the pythonista app reveals it as "2" when it should be "2.5" which is what I get when I use Python 3 on my mac.
Helping this beginner out on how I can fix this would be greatly appreciated.
-
Pythonista still uses Python 2, where the default behavior for division can be a little confusing. If at least one operand is a
float
, then the division will work normally and return afloat
. If both operands areint
s, then Python does "floor division" and rounds down the result to anint
. This is also how languages like C and Java behave (which is why Python originally did too).In Python 3, division always returns a
float
. To get the same behavior under Python 2, you can put the linefrom __future__ import division
at the top of your program. The division behavior for the interactive console can be changed in the Pythonista settings.By the way, if you want to use floor division on purpose, you can use the
//
operator, which exists on Python 3 and recent versions of Python 2. For example5.0 / 2.0 == 2.5
and5.0 // 2.0 == 2
.