-2

I'm trying to get the variable Intadd to change from the number 0, but I can't because Intadd is in the function, causing it to remain 0 no matter what. I tried moving the variable Intadd outside of the function, but then it says that Intadd is already refferenced before assignment (the only time Intadd is run in my whole code is in this function).

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

def Number_Finder():
    for x in DictionaryWords:
        Intadd = 0
        print(Intadd)
        if x.replace("\n", str(Intadd)) == Password:
            print("Congrats, you found the password!")
            break
        else:
            while Intadd < 10:
                Intadd += 1

Thanks for the help, you guys are lifesavers!

Tiger-222
  • 6,677
  • 3
  • 47
  • 60
JamesC1738
  • 25
  • 2
  • Try to manipulate with 'global' keyword: http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them – fafnir1990 Dec 12 '16 at 08:24

2 Answers2

0

The problem with your function lies in the fact that you are setting the value of Intadd on every iteration of the loop. Here's a possible alternative:

def number_finder():  # I've taken the liberty of re-writing with more Pythonic naming conventions
    intadd = 0
    for x in dictionary_words:
        print(intadd)
        if x.replace('\n', str(intadd)) == password:
            print('Congratulations...')
            break
        # et cetera

However, I have a feeling that this might still not do exactly what you hope it to. That little while loop inside the else block has exactly the same effect as just setting Intadd to 10. Additionally, since Intadd is entirely contained inside the function, as soon as the function has returned, its current value will be lost. This could be solved with the global statement or by returning the value.

Scott Colby
  • 1,370
  • 12
  • 25
0

I may have the wrong end of the stick here but you can simply return Intadd from the function.
For example:

dictfile = open('wordsEn.txt', 'r')
#DictionaryWords = dictfile.readlines()
DictionaryWords = ['hello\n', 'world\n', 'password\n', 'Quality\n', 'guess\n', '\n']
Password = "Quality5"

def Number_Finder():
    for x in DictionaryWords:
        for Intadd in range(10):
            if x.replace("\n", str(Intadd)) == Password:
                return Intadd
    return 0

Password_attempts = Number_Finder()

if Password_attempts != 0:
    print ("Congratulations, you found the password! In",Password_attempts,"attempts")
else:
    print ("Password not found")

Result:

Congratulations, you found the password! In 5 attempts
Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60