命令提示符为空白

时间:2018-04-23 06:46:45

标签: python

每当我去运行程序时,它会提示我输入名称,当我这样做它只是将你键入的行发送到下一行,我什么都不能做,但是当我关闭它时,我看到无论我怎么做c程序我看到我应该输入的任何内容#This程序按名称/打印信息搜索员工

#set a boolean value to False
found = False
#get the search value name
search = input("Enter a name to search for: ")
#open the employe file in read mode
empFile = open('employees.txt','r')
#read the first line/the name field in the 1st rec
name = empFile.readline()
#if field has records, continue processing
while name != '':
    #get id and dept
    id = empFile.readline()
    dept = empFile.readline()
    #strip newline from each string
    name = name.rstrip('\n')
    id = id.rstrip('\n')
    dept = dept.rstrip('\n')
    #determine if name matches search
    if name == search:
        #display record
        print('Name: ', name)
        print('ID: ', id)
        print('Department: ', dept)
        print()
        found = True
        #Read the name in the next record
        name = empFile.readline()
#close the file
empFile.close()
#If search item not found, print message
if found == False:
    print("The name was not found in  the file")

回溯

  

输入要搜索的名称:as Traceback(最近一次呼叫最后一次):
  文件“C:\ Users \ adam \ Desktop \ CIS201 \ searchRecords.py”,第13行,in          id = empFile.readline()文件“C:\ Users \ adam \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ encodings \ cp1252.py”,   第22行,在解码中       def decode(self,input,final = False):KeyboardInterrupt

根据要求,预期的结果应该是找到名称(或者不取决于你输入的内容)并打印名称id和部门,或者如果你输入一个不存在的名称,它应该显示错误消息“名称是没找到“

1 个答案:

答案 0 :(得分:0)

您的代码仅适用于文件中的第一个名称,因为您没有重新阅读。问题是这些行不应缩进if

    #Read the name in the next record
    name = empFile.readline()

所以,在循环中缩进:

if name == search:
    #display record
    print('Name: ', name)
    print('ID: ', id)
    print('Department: ', dept)
    print()
    found = True
#Read the name in the next record
name = empFile.readline()

可以进行许多改进,但一次只能修复一件事。