Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAdiv Abramson
6,919 Points"In Python 3, dividing two integers gives back what kind of value?" This was not covered in the lesson, AFAIK
The lesson discussed conversion/casting one data type into another, e.g. float(2) = 2.0, int('2') = 2 etc
Sometimes division of one integer by another can yield what looks like another integer, e.g. 2/1 = 2 and sometimes it can yield a float, e.g. 1/2 = 0.5
Does Python have an integer division operator "\" as in VBA? Thank you.
1 Answer
Kenneth Love
Treehouse Guest TeacherGo try it out in Workspaces. Dividing always gives back a certain type of value in Python 3.
(and, yes, we have integer/floor division, you use //
)
Kenneth Simpson
1,162 PointsKenneth Simpson
1,162 PointsCould you explain to me why it gives back a float? Floats are for decimals so why if I divide 4/2 and get 2 would that be a decimal? I am confused on that part? Thanks.
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherIt's more about having predictable and reliable behavior than it is about it being logical to our reckoning.
In Python 2, if you did
4/2
, you'd get2
. That's great. But if you did5/2
, you'd also get2
. That's...not right. But to Python, you used two integers so you must want an integer back. If you wanted a float, why didn't you use a float? (5.0/2
would give back the correct2.5
)In Python 3, they fixed this. Every division gives back a float whether you start with ints or floats. You always know you're going to get back a float, so you can then work with that appropriately.