简体   繁体   中英

Whats' wrong with my code?

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?

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!")

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!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM