Reputation: 439
So I have a dictionary which consists of a number and its definition is the corresponding element on the periodic table.
I have built up the dictionary like this:
for line in open("periodic_table.txt"):
temp.append(line.rstrip())
for t in temp:
if t[1] != " ":
elements[x] = t[3:]
else:
elements[x] = t[2:]
x += 1
I know that every element is in table because I ask the program to print the dictionary. The point of this is that the user enters a number or element name and the number and name are both printed like this:
while count == 0:
check = 0
line = input("Enter element number or element name: ")
if line == "":
count = count + 1
break
for key,value in elements.items():
if line == value:
print ("Element number for",line,"is",key)
check = 1
break
if line.isdigit():
if int(line) <= 118 and int(line) > 0:
print ("Element number",line, "is",elements[int(line)])
check = 1
break
if check == 0:
print ("That's not an element!")
This works for every element except the last one, Ununoctium, in the dictionary. When the user enters 118 this element is printed, but if they enter 'ununoctium' then the program says "That is not an element!". Why is this and how do I fix it?
Thanks in advance
Upvotes: 0
Views: 1716
Reputation: 11322
It is much easier to have python do the lookup for you. Ignoring empty lines for now:
elements = []
for line in open("periodic_table.txt"):
elements.append(line[3:])
You can then do a lookup like this:
if answer.isdigit():
print elements[int(answer)]
else:
print elements.index(answer)
Upvotes: 2
Reputation: 19252
I suspect this is a case sensitive issue.
Changing
if line == value:
to
if line.lower() == value.lower():
would solve that problem.
While you are there, why have the if
inside the for
loop?
You could check that first, and then don't need the break
if line.isdigit():
if int(line) <= 118 and int(line) > 0:
print ("Element number",line, "is",elements[int(line)])
check = 1
#<-------- break no longer required
else:
#for loop as above
Upvotes: 2