Python Forum
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Integer vs Floats
#1
Hi,

I am currently learning Python from an online course and today is my first day. I am a little confused on Integers when dividing instead of adding.

If I write


 print ((1 + 2) + 5) 
I get the answer 8 as an Integer but If I write
 print ((1 + 2) * 5 / 3) 
I get 5.0 instead of 5, why does the output give me an float instead of an Integer when I divide?

Thanks
Reply
#2
In most programming languages (Python 2 included), dividing two integers results in "integer division" which mean that the floating point part is just discarded and you end up with an integer. In Python 3, division works as you would expect. Further, any computations that involve a floating point number will result in a floating point number. In theory Python could give you an integer, since your floating point number is an integer, but it doesn't.
Reply
#3
Use // instead of / to get an integer.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  When is it safe to compare (==) two floats? Radical 4 2,702 Nov-12-2023, 11:53 AM
Last Post: PyDan
  floats 2 decimals rwahdan 3 2,472 Dec-19-2021, 10:30 PM
Last Post: snippsat
  rounding and floats Than999 2 5,091 Oct-26-2020, 09:36 PM
Last Post: deanhystad
  int, floats, eval menator01 2 3,164 Jun-26-2020, 09:03 PM
Last Post: menator01
  Stuck comparing two floats Tizzle 7 4,382 Jun-26-2020, 08:23 AM
Last Post: Tizzle
  rounding floats to a number of bits Skaperen 2 3,206 Sep-13-2019, 04:37 AM
Last Post: Skaperen
  comparing fractional parts of floats Skaperen 4 4,506 Mar-19-2019, 03:19 AM
Last Post: casevh
  Formatting floats Irhcsa 6 5,657 Oct-04-2018, 04:23 PM
Last Post: volcano63
  How do you sort a table by one column?? (of floats) sortedfunctionfails 3 14,025 Jan-11-2018, 09:04 AM
Last Post: sortedfunctionfails
  cannot convert float infinity to integer error despite rounding off floats Afterdarkreader 3 16,949 Dec-15-2017, 02:01 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020