2017-08-18 52 views
-1

我對我的代碼輸出感到困惑。Python Open File - If Else Statement

這是我的文件:

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 

我如何修復我的代碼?

+2

你的問題還不清楚。你說「有什麼方法可以修復我的代碼」,但是你沒有說明代碼應該做什麼。請查看https://stackoverflow.com/help/how-to-ask – mtrw

回答

3

您的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 =>名字典,採用快速當你有很多查詢要執行時查找(文件只讀一次,字典使用散列進行快速搜索)

+0

這很有趣。我從來沒有見過像以前那樣使用過「else」。這是否被認爲是「最佳實踐?」 –

+0

@CoryMadden - 它是語言的一部分,如果它有助於解決問題並且*可讀*,則可以使用它。 – wwii

+0

@wwii,我只是可能。我真的只是想知道是否有任何理由不使用它。有很多東西是被認爲「不好」使用的語言的一部分,比如使用'eval'。當然,一切都有它的用例,但是這有什麼缺陷應該在使用它時注意? –