How to start a loop from a number of n-digits?

Hello guys,

I want to start a for loop from a number that has n-digits. For example:

  • if n=2, then I should start the loop from 10
  • if n=4, then I should start the loop from 1000
    and so on…

That’s my code:

number == 0
 while 1:
      number += 1
      if len(str(number)) == n:
          for i in range(len(str(number))-1):
              #Do something

That works perfectly. But it takes too much time to reach the number of 5-, 6-, 7- or 8-digits. Have you any suggestions concerning the improvement of this code?

Can you think of how you can write your starting point as a power of 10?

Then you can use the range(start, end) method to create your list to loop by.

4 Likes

Thanks for the reply. It helped me a lot. There is how I did:

n = 3
for i in range(10**(n-1), 10**n):
     #Do something

The code executes more quickly.