Float Multiplying Problem

So, I wrote this code:

“num = 0.0
while True:
streq = input()
if streq == “p”:
num += 0.1
print(“Number is: {}”.format(num))”

here, every time I type p and press enter, num is supposed to be multiplied by 0.1 and printed on the screen, but after doing this a few times, it starts printing some weird numbers:

“p
Number is: 0.1
p
Number is: 0.2
p
Number is: 0.30000000000000004
p
Number is: 0.4
p
Number is: 0.5
p
Number is: 0.6
p
Number is: 0.7
p
Number is: 0.7999999999999999
p
Number is: 0.8999999999999999
p
Number is: 0.9999999999999999
p
Number is: 1.0999999999999999
p
Number is: 1.2
p
Number is: 1.3
p
Number is: 1.4000000000000001
p
Number is: 1.5000000000000002
p
Number is: 1.6000000000000003
p
Number is: 1.7000000000000004
p
Number is: 1.8000000000000005
p
Number is: 1.9000000000000006
p
Number is: 2.0000000000000004”

what am I doing wrong? please help.

Computers don’t do floating point with exact numbers: 15. Floating Point Arithmetic: Issues and Limitations — Python 3.10.2 documentation

Some of your possible alternatives:

  • Continue doing floating point, but put up with the imprecision and hide it by using round()
  • If you only need tenths, do everything 10 times bigger so it stays as integers, then divide the result by 10 for display
  • Use the Decimal module and have it add up (exact) tenths

This behaviour with floating point numbers occurs in all programming
languages, not just Python. It is an inescapable limitation of floating
point numbers.

https://docs.python.org/3/faq/design.html#why-am-i-getting-strange-results-with-simple-arithmetic-operations