如何获取变量以更改函数中的值

时间:2016-12-12 08:07:08

标签: python

我试图让变量Intadd从数字0改变,但我不能因为Intadd在函数中,导致它保持为0无论是什么。我尝试将变量Intadd移到函数之外,但之后它说Intadd在赋值之前已经被引用(在我的整个代码中运行Intadd的唯一时间是在这个函数中)

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

感谢您的帮助,您们都是救生员!

2 个答案:

答案 0 :(得分:0)

你的函数的问题在于你在循环的每次迭代中设置Intadd的值。这是一个可能的选择:

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

但是,我觉得这可能仍然没有完全符合您的希望。 while块中的小else循环与将Intadd设置为10具有完全相同的效果。此外,由于Intadd完全包含在函数内部,因此函数返回后,其当前值将丢失。这可以通过global statement或通过返回值来解决。

答案 1 :(得分:0)

我可能在这里有错误的结尾,但您可以从功能中简单地return Intadd
例如:

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

结果:

Congratulations, you found the password! In 5 attempts