I have the following code that pulls data from a given text file based on the user input:
def read_file():
students = []
f = open('file.txt', 'r')
for line in f.readlines():
data = {}
lines = ' '.join(line.split()).split()
data[''] = int(lines[5])
data[''] = float(lines[3])
data[''] = float(lines[2])
data[''] = line[1:6].rstrip(' ')
students.append(data)
def search_student(students):
student_search = input('Search for a student: ').lower()
while student_search != 'q' and student_search != 'quit':
for student in students:
if student_search in student['Student Info'].lower():
print_student_info(student)
break
student_search = input('Search for a student: ').lower()
This program returns the following output:
>>> Search for a student:
>>> allen
>>> word: Allen, Age: 12, Height: 5'4, GPA: 3.8
>>> Search for a student:
>>> quit
>>>
The input will prompt the program to pull specific data from the text file based on the word that the user inputs. This all works fine. I'm not able to figure out how to add a feature that will prompt for another input if the word is not found in the file.
Right now, if the word is not found in the file, the program just asks for another search. However, I need it to say something like "word not found in text file" before asking for another search.
This is the output I'm looking for:
>>> Search for a student:
>>> Jim
>>> Word: Jim, Age: 20, Height: 6'1, GPA: 2.5
>>> Search for a student:
>>> Molly
>>> Your searched student could not be found.
>>> Search for a student:
>>> Eddy
>>> Word: Eddy, Age: 15, Height: 5'6, GPA: 4.0
>>> Search for a student:
>>> quit
>>>
I feel like something like this should work:
def search_student(file):
student_search = input('Search for a student: ').lower()
while student_search != 'q' and student_search != 'quit':
for student in students:
if student_search in student['Student Info'].lower():
print_student_info(student)
student_search = input('Search for a student: ').lower()
else:
print("Your searched student could not be found.")
student_search = input('Search for a student: ').lower()
But it just outputs Your searched student could not be found no matter what word I input. Even typing a student that worked in the first code, now no longer works. Even typing quit no longer exits the loop. Please help.
New output:
>>> Search for a student:
>>> Allen
>>> Your searched student could not be found.
>>> Search for a student:
>>> quit
>>> Your searched student could not be found.
>>> Search for a student:
filefilebut not using that