0

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,

4

1 回答 1

0

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. 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)

于 2013-08-29T05:08:56.213 回答