【问题标题】:Python Open File - If Else StatementPython 打开文件 - If Else 语句
【发布时间】:2018-01-27 14:31:30
【问题描述】:

我对代码的输出感到困惑。

这是我的文件:

201707001 Jenson_ 
201707002 Richard 
201707003 Jean

这是我的代码:

def studentInfo (userInput):  # storing student info
    # read the students file
    with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
        for line in f:
            stdId, stdName = line.strip().split(" ", 1)
            # check if the student exist
            if userInput == stdId:
                print("Student found!")
                print("Student ID: " + stdId + "\nStudent Name: " + stdName)
            else:
                print("The student does not exist")


studentFinder = input("Please enter id: ")
studentInfo(studentFinder)

这是我的代码输出

Please enter id: 201707001
Student found!
Student ID: 201707001
Student Name: Jenson
The student does not exist
The student does not exist

如何修复我的代码?

【问题讨论】:

    标签: python if-statement text with-statement


    【解决方案1】:

    您的else 声明来得太早了。找到会输出“found”,下一行会输出“not found”!

    在到达文件末尾之前,您无法知道您没有找到学生。

    让我提出一个使用 else 对应 for 的解决方案:

        for line in f:
            stdId, stdName = line.strip().split(" ", 1)
            # check if the student exist
            if userInput == stdId:
                print("Student found!")
                print("Student ID: " + stdId + "\nStudent Name: " + stdName)
                break
        else:
            print("The student does not exist")
    

    现在如果找到学生,请致电break。如果未调用break,则进入for 循环的else。不错的python特性,鲜为人知

    (如果要匹配多次则不起作用)。

    请注意,从长远来看,您可能希望将文件内容存储在字典中,以便多次搜索时查找速度更快:

    with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
        d = dict(zip(line.split(" ",1) for line in f)
    

    现在d 是您的 id => 名称字典,当您有很多查询要执行时使用快速查找(文件只读取一次,字典使用哈希进行快速搜索)

    【讨论】:

    • 这很有趣。我以前从未见过像这样使用else。这被认为是“最佳实践”吗?
    • @CoryMadden - 它是语言的一部分,如果它有助于解决问题并且可读,请使用它。
    • @wwii 我可能会。我真的只是想知道是否有任何理由不使用它。语言中有很多东西被认为是“不好”使用的,例如使用eval。当然每样东西都有它的用例,但是在使用它时有什么需要注意的陷阱吗?
    • 这是一种非常有趣的语言。谢谢你的回答
    • @CoryMadden 它避免使用标志。 eval 不好,因为它不安全(代码注入)。不是这里的情况。感谢您的支持:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-23
    • 2019-04-09
    • 2020-06-07
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多