1

I want to use just 1 loop in python to obtain the sequence like (likes counter in second and miliseconds)

0 0.033 0.066 0.1 0.133 0.166 0.2....

Currently, I have to use two loops to obtain it as follows

miliseconds =[0 0.033 0.066 0.1 0.133 0.166 0.2 0.233 0.266 0.3 0.333 0.366 0.4 0.433 0.466 0.5 0.533 0.566 0.6 0.633 0.666 0.7 0.733 0.766 0.8 0.833 0.866 0.9 0.933 0.966 1]
for second in range(100):
   for milisecond_ in miliseconds:
       print (second + milisecond_)
1
  • 1
    0.033 milliseconds is 33 microseconds. Deal with integers as much as possible when programming. Commented Nov 1, 2022 at 20:31

1 Answer 1

3

Use mathematics:

# You can change second to '100'
second = 3
for i in range((30 * second)+1):
    print(round(i/30, 4))
    
    # If you want to get full precision -> uncomment below line
    # print(i/30)

Output:

0.0
0.0333
0.0667
0.1
0.1333
0.1667
0.2
0.2333
...
2.7333
2.7667
2.8
2.8333
2.8667
2.9
2.9333
2.9667
3.0
Sign up to request clarification or add additional context in comments.

6 Comments

A round(i, 4) could be nice with that
@azro rounding wouldn't produce the exact numbers given in the question. Better to leave them with full precision or use a custom truncation function.
Great solution. However if I just want to print number like x.033 x.066 x.1 where x is second instead of x.0333 x.0667 x.1. Is it possible to do it?
@MoonLee, maybe change print(round(i/30, 4)) -> print(round(i/30, 3)). Are you wanting this?
Round 3 will gives 0.067 instead of 0.066
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.