【问题标题】:python-block try/except - display a line of textpython-block try/except - 显示一行文本
【发布时间】:2021-06-22 12:51:57
【问题描述】:

我的代码:

  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()

如何添加异常(try/except)处理,这样在输入后,例如不存在的第30行的编号,就会出现异常,例如“该行不存在”,我有一个大问题,有人可以帮忙吗?

提前致谢!!!

【问题讨论】:

    标签: python loops for-loop exception try-catch


    【解决方案1】:

    你真的不需要try / exceptif 声明就可以了:

    ...
    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!)
    ...
    

    (我猜你正在制作程序,以便用户输入基于 1 的索引,所以 elif 条件有 &gt; 而不是 &gt;=。)

    但是如果你确实需要try / except,这里是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
    
    ...
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

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

      但你也可以检查它是否有效:

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

      (在另一个响应中注意到您使用的是 1-indexed 而不是 0-indexed) 个人认为输入“0”不是一个好的退出条件。

      【讨论】:

        猜你喜欢
        • 2021-06-22
        • 2019-06-26
        • 1970-01-01
        • 2020-12-11
        • 2020-03-29
        • 1970-01-01
        • 1970-01-01
        • 2011-04-25
        • 2018-03-19
        相关资源
        最近更新 更多