简体   繁体   English

需要Python文件帮助

[英]Python Files help needed

my program works fine checking the file with periodic table number and elements with this program: 我的程序可以使用此程序很好地检查具有周期表编号和元素的文件:

userline=input('Enter element number or element name: ')
userline=userline.capitalize()
f=open('periodic_table.txt')
while userline:
 for line in f:
   number,element=line.split()

but if i add to the program like this: 但是如果我这样添加到程序中:

   else:
     print('Thats not an element!')
     userline=input('Enter element number or element name: ')
     userline=userline.capitalize()

it keep printing that not an element even if we put correct number of element or correct name, 即使我们输入正确数量的元素或正确的名称,它也会继续打印该元素

The reason why your current approach isn't working is because you're iterating through a list. 您当前的方法行不通的原因是,您正在遍历列表。 If you do userline != element , the very first time you encounter an element or number that isn't equal to the user input, the program will print the error message. 如果执行userline != element ,则第一次遇到不等于用户输入的元素或数字时,程序将打印错误消息。 Since you're looping through every periodic table element, you're going to get a bunch of error messages! 由于您遍历每个元素周期表元素,因此您将获得一堆错误消息!

Instead, try first adding each periodic table element and number into a dictionary or list. 相反,请尝试首先将每个元素周期表元素和编号添加到字典或列表中。 That way, you can check if what the user typed in is inside the dictionary, and return an error message without having to loop through the entire thing. 这样,您可以检查用户键入的内容是否在字典中,并返回错误消息,而无需遍历整个内容。

Here's a short example of what you might want to try instead: 这是您想尝试的简短示例:

# The "with" statement automatically closes the file for you!
with open('periodic_table.txt') as f:  
    numbers = {}
    elements = {}
    for line in f:
        num, element = line.split()
        numbers[num] = element
        elements[element] = num

while True:
    userline = input('Enter element number or element name: ')
    userline = userline.capitalize()

    if userline in numbers:
        print('Element number ' + userline + ' is ' + numbers[userline])
    elif userline in elements:
        print('Element number for ' + userline + ' is ' + elements[userline])
    else:
        print("That's not real!")

(Caveat: I didn't try running this, so you might have to tweak it a bit to make sure it works properly) (注意:我没有尝试运行此程序,因此您可能需要对其进行一些调整以确保其正常工作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM