2016-12-12 30 views
-2

変数Intaddを数値0から変更しようとしていますが、Intaddが関数に含まれているため0になりません何。変数Intaddを関数外に移動しようとしましたが、割り当て前にIntaddがすでにrefferencedされています(私のコード全体で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 

お世話になりました!

+0

は、 'グローバル' のキーワードで操作しよう: http://stackoverflow.com/questions/423379/using-global-variables-in- a-function-the-one-that-c​​reated-themそれら以外の機能 – fafnir1990

答えて

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で解決するか、値を返すことで解決できます。

0

ここではスティックの端が間違っている可能性がありますが、機能からはreturnIntaddとすることができます。たとえば

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 
関連する問題