2

My code:

  fname = "text.txt"
text_file = open(fname, "r")
lines = text_file.readlines()
while True:
    linenumber = int(input("Please enter a line number or press 0 to quit:  "))
    if linenumber == 0:
        print("Thanks for using the program")
        break
text_file.close()

How can I add an exception(try/except) handling, so that after entering, for example, the number of line 30 which does not exist, an exception appears, eg "This line does not exist", I have a big problem with it, could someone help?

Thanks in advance!!!

2 Answers2

1

You don't really need try / except for that; an if statement will do:

...
while True:
    linenumber = int(input("Please enter a line number or press 0 to quit:  "))
    if linenumber == 0:
        print("Thanks for using the program")
        break
    elif linenumber < 0 or linenumber > len(lines):
        print("this line doesn't exist!)
...

(I guess you're making the program so that user enters 1-based indexing, so the elif condition has > instead of >=.)

But if you do need try / except, here is one way of EAFP:

...
while True:
    linenumber = int(input("Please enter a line number or press 0 to quit:  "))
    if linenumber == 0:
        print("Thanks for using the program")
        break

    try:
        lines[linenumber-1]
    except IndexError:
        print("This line does not exist")
    else:
        print("this line exists, yes")
        # do what you'd do when it exists

...
Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38
0

You can do:

try:
    print(lines[linenumber])
except IndexError:
    print("Line not found")

But you could just check if it's valid as well:

if len(lines) < linenumber:
    print("line not found")

(Noticed as in the other response that you are using 1-indexed rather than 0-indexed) Personally I don't think entering "0" is a good exit condition.

Ed OBrien
  • 76
  • 4