Home > other >  Why does my for loop run indefinitely and doesn't stop when the if condition is met?
Why does my for loop run indefinitely and doesn't stop when the if condition is met?

Time:01-21

I'm trying to read text from a file and using a loop to find a specific text from the file. The data in the file is listed vertically word by word. When I run the script, after it prints the last word in the file it repeats itself from the beginning indefinitely.

with open('dictionary.txt','r') as file:
    dictionary = file.read().strip()
for i in dictionary:
 print (dictionary)
 if( i == "ffff" ):
    break

CodePudding user response:

first split the lines by "\n" then print(i) not print(dictionary):

with open('dictionary.txt', 'r') as file:
    dictionary = file.read().strip().split("\n")
for i in dictionary:
    print(i)
    if i == "ffff":
        break

CodePudding user response:

before, you should split the lines b/c it will loop into the string and check if the characters are ffff, and it won't be True

i will be a single character, so you should do first

dictionary = dictionary.split("\n")

BUT if your ffff is a line, if is a word separated with spaces you can do:

dictionary = dictionary.split(" ")
  •  Tags:  
  • Related