for循环后打印一次

时间:2017-11-23 17:15:21

标签: python for-loop

for line in infileStudents:
    line = line.rstrip()
    parts = line.split(':')
    studentID = int(parts[0])
    studentName = parts[1]
    if studentID == ID:
       break
    else:
       print("No record")

我正在尝试在文件中搜索ID号,如果文件中不存在该ID,则打印一条消息。

上面的代码读取每一行并为每一行打印一条消息。

在读取文件中的所有ID后,如何只打印一条消息?

2 个答案:

答案 0 :(得分:0)

请尝试此代码。

idFound =  False         # variable declared as a flag with default False
for line in infileStudents:
    line = line.rstrip()
    parts = line.split(':')
    studentID = int(parts[0])
    studentName = parts[1]
    if studentID == ID:
       idFound = True    # if Id found then changing flag variable to true to handle further excution of the code
       break

if idFound:   # handling here
   print("Id found")
else:
   print ("No record")

答案 1 :(得分:0)

site-packages

试试这个。当您可以使用if line not in infileStudents.read(): print ("No record") 时,无需搜索每一行,并检查整个文件是in是否为字符串。