Python Python Basics Types and Branching Numeric

Radovan Valachovic
PRO
Radovan Valachovic
Python Web Development Techdegree Graduate 13,975 Points

Floats

Question in regards of your video - how come when you do 16/4 the Workspace output is 4.0 - you dividing integers so output should be an integer. I have tried it in the terminal of my mac and output is integer 4 - even is you do previous 4+1.5 = 5.5 is float and then 16/4 = 4 integer - probably you have a bug in the workspace.

8 Answers

Sal Campagna
Sal Campagna
3,539 Points

Noticed on my mac when running "python" (2.7.10) 16/4 returns 4, however, if I run "python3" (3.6.4) it returns 4.0. The workspace is running 3.6.4 as well, so it returning a float is correct.

However in Python3, if you do 16//4 it will return an integer.

Note: even with // if either of the numbers is a float, it will return the float.

Phil Thomas
Phil Thomas
4,562 Points

This is discussed in the teachers notes, which contains a link to a full explanation in the Python documentation:

https://docs.python.org/3/tutorial/floatingpoint.html

Radovan Valachovic
PRO
Radovan Valachovic
Python Web Development Techdegree Graduate 13,975 Points

I figure that out in python 2.7 is 0.1+0.1+0.1 = 0.30000000000000004 but in python 3 it is precisely 0.3 - question is why

It also discussed in the video itself, the operation returns a float. If you wish to have integer division. You can do the following operations

23 // 3
23 % 4 #this will give you the remainder 
Hai Phan
Hai Phan
2,442 Points

Craig said you always will get a float when you do devision, and it true when I do 16/4 in my Windows PC, always 4.0

Radovan Valachovic
Radovan Valachovic
Python Web Development Techdegree Graduate 13,975 Points

Try it for python2.7 and python3 you will see. I am doing it in Linux and macOS terminal - 2.7 - float, python3 - integer

Jason Anders
Jason Anders
Treehouse Moderator 143,823 Points

Radovan Valachovic

I think you have it backwards. In Python 2.7, the / is an integer division symbol and will return and integer. In Python 3, the / is the floating point division symbol and the // is the integer division symbol.

This can be found in the Development notes for Python, or a more clear explanation in this Stack Overflow thread

Keep Coding! :) :dizzy:

now this session start very complicated. hard to understand.

plz make an simple video its hard to understand

Remy Duijsens
Remy Duijsens
970 Points

This is because there are different Python version used. Python updates from time to time, currently the community is separated in the "old" Python version 2.7 and the newer version Python 3.7. The Workspace uses this newer version which comes with new functionalities. The division operator (/) now always returns answers as floating point number. If you wish to use the old functionality you have to use a double forward slash (//) for integer division. You could of course also download the newer version of python at python.org!