Skip to content
Advertisement

Printing lines in a text file given line numbers

I am having trouble with a while loop statement for the question below. This is for a txt.file.

‘Write a program that allows the user to navigate through the lines of text in any text file. The program prompts the user for a filename and copies the lines of text from the file into a list. The program then prints the number of lines in the file and prompts the user for a line number. Actual line numbers range from 1 to the number of lines in the file. If the input is 0, the program quits. Otherwise, the program prints the text in that line number.’

Please see my code.

JavaScript

When I run the program, the line number does not print after I enter a line number.

Obviously, I am not using the while loop correctly here. Can someone please tell me what I am doing wrong here? Can I possibly use a def function here?

Thanks!

Advertisement

Answer

Move line linenum = 0 inside the While True: loop.

The linenum variable must be reset to 0 (linenum = 0) when the program re-enters the loop. Otherwise the linenum variable will always keep being incremented and have a value that is greater than num and will never trigger the if statement to print the line at that number.

Your code with linenum = 0 in the loop:

JavaScript

Alternative method:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement