2

I want a program to print this output in the terminal :

0000
0001
0002
...
0010
0011
...
9990
9991
...

Because I wanted to find all 4-digit pincodes with 0 to 9 digits.

So I started writing this program in python :

num = ""
for a in range(0 , 10) :
num += str(a)
for b in range(0 , 10) :
    num += str(b)
    for c in range(0 , 10) :
        num += str(c)
        for d in range(0 , 10) :
            num += str(d))
            print(num)
            num = ""

But I received this output :

2
3
4
5
6
7
8
9
9000
1
2
...
30
...
100
...

So I decided to test another program :

num = []

for a in range(0 , 10) :
    num.append(str(a))
    for b in range(0 , 10) :
        num.append(str(b))
        for c in range(0 , 10) :
            num.append(str(c))
            for d in range(0 , 10) :
                num.append(str(d))
                print(num)
                num = []

But again I didn't succeed :

['2']
['3']
['4']
['5']
['6']
['7']
['8']
['9']
['9', '0', '0', '0']
...
['4']
['5']
...
['7']
...
['9', '0']
...
['9']
['9', '0', '0']
...
['5', '0']
['1']
...
['6', '0']
...
['7', '0']
...
['8', '0']
...
['9', '0']
['1']
['2']
['3']
['4']
...
['9']

Does anybody knows how to solve this problem?

  • I see these are consecutive numbers, why not print a counter with left padding of 4? – CodeTalker Jul 21 '21 at 10:11
  • `[str(i).zfill(4) for i in range(0, 10000)]` – Epsi95 Jul 21 '21 at 10:11
  • If you really want to try all numbers from 0000 to 9999, why don't you use a counter and increase it normally? You can eventually pad the missing zeroes to the left (for example, 1 is 0001, you just add three zeroes to the left). – Nastor Jul 21 '21 at 10:11

4 Answers4

2

What about the blindingly obvious?

for i in range(10000):
    print('%04i' % (i))

Perhaps also notice that range implicitly runs from 0 if you only pass one argument; you don't need to separately spell this out.

tripleee
  • 175,061
  • 34
  • 275
  • 318
2

It would be much more straightforward to simply run:

for i in range(10000):
    print(f"{i:04}")

See also this SO question on zero-padding strings in Python.

If you really want to use nested for-loops, I'd rather do the following:

for a in range(0, 10):
    for b in range(0, 10):
        for c in range(0, 10):
            for d in range(0, 10):
                num = f"{a}{b}{c}{d}"
                print(num)
Daniel Lenz
  • 3,334
  • 17
  • 36
1

There is also the option of using .zfill() which is a built-in:

for i in range(10000):
    print(str(i).zfill(4))
Matiiss
  • 5,970
  • 2
  • 12
  • 29
0

You can also do it with the use of lists.

for i in range(10000):
    r = 4-len(list(str(i)))
    r = ['0']*r
    print(''.join(r)+str(i))

Here you are only checking the lengths, and using join for the final string.