I wrote the following program. The program is supposed to get the name of a file having some chemical data and an input from the user to determine if the element is already one of the elements of the file or not. But unfortunately, in the first step, I receive this message that enter a valid name for the file. I don't know where the problem is?! Any help is really appreciated.
# Determine the name of a chemical element
import re
# Read the name of a file from the user
filename = input("Enter a filename:")
try:
# Open the file
f1 = open(filename, "r")
# Read an element from the user
elem = input(
"Enter the name of the element or the number of protons (" * " to exit): "
)
while elem != "*":
try:
int_elem = int(elem)
# Search in each line for the entered input
for line in f1:
if re.findall(elem, line) != []:
# Split the line to its elements
elem_line = line.split(" ")
# Print the name of element
print("The name of element is {}".format(elem_line[0]))
# print the symbol of the elemnt
print("The symbol of element is {}".format(elem_line[1]))
# Print the number of elements
print(
"The number of protons in {} is {}".format(
elem_line[0], elem_line[2]
)
)
else:
# Display if there is no elemt with this number of protons
print("There is no element with this number of protons")
break
except:
# Serach for th element in each line of the file
for line in f1:
if re.findall(elem, line) != []:
# Split the line to its elements
elem_line = line.split(" ")
# Print the number of elements
print(
"The number of protons in {} is {}".format(
elem_line[0], elem_line[2]
)
)
elem = input("Enter the name of the lement(" * " to exit):")
except:
print(" Enter a valid name for the file ")
If I run the program, I will get the following output:
Enter a filename:'chemic.txt'
Enter a valid name for the file