我有一个名为“periodic_table”的文件。这个文件里面有多行。每一行都有一个原子序数,右边有一个相应的元素名称,如下所示:
1 Hydrogen
2 Helium
3 Lithium
4 Beryllium
5 Boron
6 Carbon
7 Nitrogen
8 Oxygen
9 Fluorine
10 Neon
11 Sodium
12 Magnesium
13 Aluminium
14 Silicon
etc...
我制作了一个程序,要求输入元素名称或数字,并打印出字典中的相应值。如果用户输入1,它将打印氢气,类似地,如果用户输入硅,它将输出14.但是 - 我希望程序通知用户他是否输入不存在的原子序数(例如150)或不存在的元素(如Blanket或任何其他字符串)。我尝试使用if
,但它打印出一个无限循环:
element_list = {}
name = input("Enter element number or element name: ")
while name:
with open("periodic_table.txt") as f:
for line in f:
(key, val) = line.split()
element_list[int(key)] = val
if name == key:
print(val)
elif name == val:
print(key)
name = input("Enter element number or element name: ")
答案 0 :(得分:4)
对于现有代码的最小更改,如果找到该元素,则可以设置标记found
,并相应地对其进行操作。所以:
found = False
for line in f:
# ....
if name == key:
print(val)
found = True
elif ...
if not found:
print("Not an element or atomic number: {}".format(name))
答案 1 :(得分:2)
您可以在找到匹配后立即退出程序。如果未找到匹配项,将再次提示用户输入。否则程序将在打印相应的号码/名称后终止。
# http://docs.python.org/2/library/sys.html
import sys
#variable below is not doing much!
#element_list = {}
name = input("Enter element number or element name: ")
#Changed loop to be infinite
while True:
with open("periodic_table.txt") as f:
for line in f:
(key, val) = line.split()
element_list[int(key)] = val
if name == key:
print(val)
sys.exit()
elif name == val:
print(key)
sys.exit()
#If something is found, it will never reach this
print("No match found... try again!")
name = input("Enter element number or element name: ")
答案 2 :(得分:1)
要有效地解决此问题(不重复读取文件),您需要将其分解为两个步骤,当前代码混合在一起。首先,读取文件并准备元素名称和数字之间的字典映射。其次,处理用户输入并检查字典。
# step 1, build the mapping
element_list = {}
with open("periodic_table.txt") as f:
for line in f:
number, name = line.split()
element_list[number] = name
element_list[name] = number # map in both directions
# step 2, test user input (quits after an empty input)
user_entry = input("Enter element number or name: ")
while user_entry:
try:
print(element_list[user_entry])
except KeyError:
print("Unrecognized number or name.")
user_entry = input("Enter element number or name: ")