Search code examples
python-3.xfor-loopnested-loops

Why I am not able to Iterate my first FOR loop


I am writing a python code to find all possible combinations of password with specific rules

  1. should contain alphabets A-Z a-z
  2. should contain numbers 0-9
  3. should contain special symbols
  4. first character of password must be capital letter
from itertools import permutations

pw = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789[@_!#$%^&*()<>?/\|}{~:]"
firstchar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

c = permutations(pw, 2) #3 is the password length for providing sample output quickly
f=open("password.txt","w+")
f.truncate(0)

for x in firstchar:
    for i in c: 
        current_pw = x + "".join(i)
        f.write( "\t" + current_pw + "\n" )

** the output contains only password starting from A and stops doesn't iterate for B, C... **


Solution

  • I think permutation quits after the first loop. So you define c in each loop.

    from itertools import permutations
    
    pw = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789[@_!#$%^&*()<>?/\|}{~:]"
    firstchar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    
    f=open("password.txt","w+")
    f.truncate(0)
    
    for x in firstchar:
        c = permutations(pw, 2)          # c is defined here
        for i in c: 
            current_pw = x + "".join(i)
            f.write( "\t" + current_pw + "\n" )