Hello I need a little explanation. Im a beginner | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Hello I need a little explanation. Im a beginner

x = float(input()) while x <= 200: if x%2 == 0: print(str(x) + " is even") else: print(str(x) + " is odd") x += 0.1 When I run this following code and I type 0 as the input, why does not just increase by 0.1 and randomly. For example one of the outputted lines was like 0.39999999... Please explain clear and concise id appreciate it this is python

19th Jun 2021, 10:18 PM
Zane Al-Hamwy
Zane Al-Hamwy - avatar
3 Answers
+ 6
visph gave you the answer. To fix it, you can round x to the nearest single decimal place by changing x += 0.1 to x = round(x + 0.1, 1)
19th Jun 2021, 11:42 PM
David Ashton
David Ashton - avatar
+ 5
as in many languages, python internally store float as binary floating point with a fixed prevision... so some values expressed as decimal are a few innacurate ^^ more detailled explanation here: https://www.geeksforgeeks.org/floating-point-error-in-python/
19th Jun 2021, 10:28 PM
visph
visph - avatar
+ 1
You need to learn while and for loop first and your code only excutes ones
21st Jun 2021, 6:09 PM
Predator
Predator - avatar