0

There is a better way to write this code:

for i in range(50, 56, 1): print(i / 10) print("Half way done!") for k in range(56, 61, 1): print(k / 10) print("All the way done!") 

Output:

5.0 5.1 5.2 5.3 5.4 5.5 Half way done! 5.6 5.7 5.8 5.9 6.0 All the way done! 

I've been trying to compare floating point numbers and this is the best I have gotten so far, there are methods out there but I cant understand them as I'm not at that level yet, so if anyone could provide an alternative way of comparing floating point numbers, that would be much appreciated. Thanks!

2
  • 1
    You're not actually performing any floating-point comparison here. What are you trying to learn? Do you want to learn something about comparing floating-point numbers? Or do you want to learn something about performing an action halfway through a loop? Commented Mar 27, 2017 at 6:13
  • I'm trying to learn an action halfway through a loop, by comparing floating point numbers, I could have word my question better! the output needs to be the same. Commented Mar 27, 2017 at 6:16

1 Answer 1

2

Instead of trying to compare i/10 to 5.5, simply compare the loop iterator (which is an integer) to the calculated halfway point (another integer):

start = 50 end = 61 half = (end-start)//2 + start for i in range(50, 61): print(i/10) if i == half: print('Half way done!') print("All the way done!") 
Sign up to request clarification or add additional context in comments.

6 Comments

this got me thinking, is there a way for me to do something along the lines of adding a 0.1 to 50 making it 50.1 and giving the same output?
@Adem - I'm not sure what you mean. Can you clarify?
taking floating point numbers from the start and instead of "/" the value, making it so it adds the value "0.1" to say 50 so result= 50.1 and repeats this process from start till end, giving the same output
@Adem - You could do i = 5 and then for i in range(10): i += 0.1 with print(i) and an if math.isclose(i, 5.5): print('Half way done!') (note that math.isclose is available starting in Python 3.5). There are several ways to accomplish this.
I'm however using python 3.4, in which I cant seem to do math.isclose
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.