How to fix this problem with nested for loops in python?

Viewed 75

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?

4 Answers

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.

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)

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

for i in range(10000):
    print(str(i).zfill(4))

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.

Related