def decode():
results = {}
steps = 2
postNumber = 1
with open('Example.txt') as txt_file:
for line in txt_file:
key, value = line.strip().split(' ')
results[int(key)] = str(value)
for key, value in results.items():
if postNumber == key:
print(key, value)
postNumber += steps
steps += 1
decode()
With the code above, I am currently trying to make a Python Script that reads the file “Example.txt” containing lines “6 q 1 r 3 p” where each number and letter pair are separated by newlines. They are then stored into a dictionary where the numbers are keys (stored as integers) and the letters are values (stored as strings). I am trying to make it where if postNumber matches with the value of the key the for statement iterates over, it prints the key value pair, then updating postNumber with the amount of steps and updating steps by one. The goal is to make it print each key value pair as
1 r
3 p
6 q
However, when I try to run it, it doesn’t give me any output. When I remove postNumber += steps and steps += 1 from the code, I get
1 r
Then it goes back to giving me no output at all the second I put the two variable equations back into the code, which doesn’t make sense to me, especially considering it happens AFTER the if statement so it has to at least print “1 r” and it’s not embedded within the if statement; only the for statement.
I have tried adding an else statement and making both it and the if statement have the postNumber += steps and steps += 1 to see if it would change anything to no avail.
sheenathon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.