0

I'm trying to make a password cracker for a project at school, but I've run into a problem. Here's the code:

dictfile = open('c:/ScienceFairDictionaryFolder/wordsEn.txt', 'r')
DictionaryWords = dictfile.readlines()

Password = "abductors"

for x in DictionaryWords:
    if x is Password:
        print("Found it!")
    else:
        print("This password can't be guessed!")

So everytime I run this code, I only get:

"This password can't be guessed!"

However, I made sure the word was in the dictionary I'm using, so I don't understand why the password isn't being guessed. Is there something I'm doing wrong with the code I'm using?

1
  • 4
    1: Don't use is for string comparisons. Use ==. 2: You have to remove the line ends: if x.strip('\r\n') == Password:. Commented Dec 11, 2016 at 21:15

2 Answers 2

1

You need to change two things with your code: Use == for string comparisons and remove the newline (\n) character by replacing it.

dictfile = open('wordsEn.txt', 'r')
DictionaryWords = dictfile.readlines()

Password = "abductors"

for x in DictionaryWords:
    if x.replace("\n", "") == Password:
        print("Found it!")

    else:
        print("This password can't be guessed!")
Sign up to request clarification or add additional context in comments.

Comments

1

Stepwise description of the suggested approach:

  1. Read the file content using the read() method instead of readlines().
  2. Generate a list of words using the split() method. This also removes the newline characters.
  3. Check whether the password is in the dictionary through the in operator. This allows you to get rid of the for loop.

This snippet should get the job done:

with open('c:/ScienceFairDictionaryFolder/wordsEn.txt', 'r') as dictfile:
    DictionaryWords = dictfile.read().split('\n')

Password = "abductors"

if Password in DictionaryWords:
    print("Found it!")
else:
    print("This password can't be guessed!")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.