Будет трудно понять, в чем проблема, поскольку все исключения, возникающие в вашем коде, "проглатываются" этим блоком except:
верхнего уровня.
Оборачивает всю вашу программу вобработчик исключений не является хорошей формой - вместо этого обрабатывайте ошибки (или не делайте!) ваш пользователь получит, например, FileNotFoundError
, что, вероятно, более чем подходит) по мере их возникновения.
Что-то подобное можетработа для вас.
import re
filename = input("Enter a filename:")
f1 = open(filename, "r")
while True:
f1.seek(0) # We need to be at the start of the file for every user input.
# Read an element from the user
elem = input("Enter the name of the element or the number of protons (* to exit): ")
if elem == "*":
break # exit the loop
# Search in each line for the entered input
for line in f1:
if re.search(elem, line):
# Split the line to its elements
elem_line = line.split(" ")
print("The name of element is {}".format(elem_line[0]))
print("The symbol of element is {}".format(elem_line[1]))
print("The number of protons in {} is {}".format(elem_line[0], elem_line[2]))
break # found a match, exit the loop
else:
print("There is no element with this name or number of protons")