全局的Python问题?

时间:2017-01-07 21:50:07

标签: python

我尝试使用python为项目创建密码猜测器。但是,我已经陷入困境。这是我目前正在使用的代码。

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


Password = 'zygote10'

Intadd = 0

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


def Password_Tester():
    for x in DictionaryWords:
        if x .replace("\n", "") == Password:
            print('Found it!', x, 'is the password!')
            break
    else:
        Number_Finder()


Password_Tester()

当我运行代码时,我希望看到类似的内容:

apple1
apple2
apple3
apple4
apple5
apple6
apple7
apple8
apple9
apple10
ate1
ate2

等等。 (基本上我希望代码运行一个单词,每次更改数字,直到其中的数字达到10,然后更改单词,然后重复该过程)。

然而,当我运行代码时,我看到了:

apple1
apple2
apple3
apple4
apple5
apple6
apple7
apple8
apple9
apple10
ate10
aviation10

(在苹果之后,单词不要重复从1到10的过程,然后单词会随着数字10的变化而变化)

我认为问题在于全球指挥。我对Python很新,所以如果这是一个明显的解决方案,我很抱歉。谢谢你们!

1 个答案:

答案 0 :(得分:0)

一般情况下不应使用global,因此本地变量和for循环:

def Number_Finder():
    for x in DictionaryWords:
        for n in range(10):
            x2 = x.strip()+str(n)
            print(x2)
            if x2 == Password:
                print("Congrats, you found the password!")
                return