Hello! I am writing a code using Python but I am having issues with the while loop. It seems repetitive too. I am trying to open a file, and I want to read each line of that file until last line. Each time I read a line I want to split that string into a list and assing the position 0 of the list to variable initialWord and the position 1 of the list to variable endWord and then print it. The file I am opening just has lines with two words each line. When I call my function I get an error. I also want to clean the code because it seems repetive but If I get rid of the top part outside the while loop I noticed the first line in the file was not being printed.. the loop starts from second line. I am attaching a picture of the output I want and the error that it shows and picture of how the file forTest.txt looks like.. actually the code is supossed to work with any file that is similar to the one I am using there is no way to know how many lines the file will have.. Here is my code: def pairOfWords(): pairOfWords = open("forTest.txt", "r") lineWithWords = pairOfWords.readline() L= lineWithWords.split() initialWord= L[0] endWord= L[1] print("Initial:"+ initialWord , "end:" + endWord) while lineWithWords: lineWithWords= pairOfWords.readline() L= lineWithWords.split() initialWord= L[0] endWord= L[1] print("Initial:"+ initialWord , "end:" + endWord) pairOfWords()
Hello! I am writing a code using Python but I am having issues with the while loop. It seems repetitive too.
I am trying to open a file, and I want to read each line of that file until last line. Each time I read a line I want to split that string into a list and assing the position 0 of the list to variable initialWord and the position 1 of the list to variable endWord and then print it. The file I am opening just has lines with two words each line. When I call my function I get an error. I also want to clean the code because it seems repetive but If I get rid of the top part outside the while loop I noticed the first line in the file was not being printed.. the loop starts from second line.
I am attaching a picture of the output I want and the error that it shows and picture of how the file forTest.txt looks like.. actually the code is supossed to work with any file that is similar to the one I am using there is no way to know how many lines the file will have..
Here is my code:
def pairOfWords():
pairOfWords = open("forTest.txt", "r")
lineWithWords = pairOfWords.readline()
L= lineWithWords.split()
initialWord= L[0]
endWord= L[1]
print("Initial:"+ initialWord , "end:" + endWord)
while lineWithWords:
lineWithWords= pairOfWords.readline()
L= lineWithWords.split()
initialWord= L[0]
endWord= L[1]
print("Initial:"+ initialWord , "end:" + endWord)
pairOfWords()
Step by step
Solved in 4 steps with 3 images