Home > other >  Number generator from 1-9999
Number generator from 1-9999

Time:02-27

I created a number generator to create numbers from 0001 to 9999 but ended up creating 1 without the zeros:

1
2
3
etc.

code I am using:

def my_gen(start, end, step):
    while start < end:
        start  = step
        yield start

for x in my_gen(1, 1000, 2):
    print x

CodePudding user response:

Zeros on the left side of the int objects are not permitted, Python gives you SyntaxError. In math there is no difference between 0001 and 1.

Instead you can have str. "0001" is now different from "1".

with zfill - compatible with Python 2.7:

for x in range(1, 100, 2):
    print(str(x).zfill(4))

or with f-string - Python 3.6 :

for x in range(1, 100, 2):
    print(f"{x:04}")

With format() compatible with Python 2.7:

for x in range(1, 100, 2):
    print(format(x, '04'))

CodePudding user response:

If you need strings, note that you could use itertools.product for this purpose:

from itertools import product

my_gen = map(''.join, (product('0123456789', repeat=4)))
list(my_gen)
# ['0000', '0001', ... '9999']
  • Related