0

I want to use the variable "i" created in poss = [j.split() for j in [decipher(i, txt) for i in range(1, 26)]], but it raises a NameError when I try to access it in line return f"The key is {i} and the deciphered text is{' '.join(k)}.". Is there any way to do this without raising an error?

popular = open("C:/Users/NAME/FilesForPyCharm/popular.txt")
words = [line.strip() for line in popular]
poss = [j.split() for j in [decipher(i, txt) for i in range(1, 26)]]
for k in poss:
    if set(k).issubset(set(words)):
        return f"The key is {i} and the deciphered text is{' '.join(k)}."
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Kai036
  • 190
  • 1
  • 2
  • 10
  • i is only defined in list comprehension. You can put 25 directly as this is the end value, so it's probably not the proper way to go, the loop doesn't short-circuit – Jean-François Fabre Mar 06 '19 at 02:24
  • `poss = [(i, decipher(i, txt).split()) for i in range(1, 26)]` and then `for i,k in poss:...` – khachik Mar 06 '19 at 02:26
  • The i gets assigned all the values from 1 to 25, which of these should be used and when in your print string? – ruohola Mar 06 '19 at 02:26
  • @Jean-FrançoisFabre: I had a look at the duplicate target question that you mentioned, and there doesn't seem to be any duplication at alll. Of course, I did not read every answer to that question to see if any of those answers coincidentally happened to have answer for this one too. – fountainhead Mar 06 '19 at 09:38

1 Answers1

0

You could save the value of i with its corresponding element and then loop over the pairs:

popular = open("C:/Users/NAME/FilesForPyCharm/popular.txt")
words = [line.strip() for line in popular]
poss = [(j.split(), i) for j in [decipher(i, txt) for i in range(1, 26)]]
for k, i in poss:
    if set(k).issubset(set(words)):
        return f"The key is {i} and the deciphered text is{' '.join(k)}."
ruohola
  • 21,987
  • 6
  • 62
  • 97