I have a list which looks like this: [1 H 1.0079, 2 He 4.0026, 3 Li 6.941, 4 Be 9.01218, ...] I want to ask the user of the program for the corresponding atomic number to the atom. So the program will take a random atomic symbol and ask the user what's the atoms atomic number.
Code so far:
class Atom:
def __init__(self, number, weight, atom):
self.number = nummer
self.atom = atom
self.weight = weight
def __str__(self):
return self.atom " " str(self.weight)
def __repr__(self):
return str(self.number) " " self.atom " " str(self.weight)
def atom_listan():
atom_file = open('atomer2.txt', 'r')
atom_lista = []
number = 1
for line in atom_fil:
data = line
weight = float(data.split()[1])
atom = data.split()[0]
new_atom1 = Atom(number, weight, atom)
atom_lista.append(new_atom1)
atom_lista.sort(key=lambda x: x.vikt)
atom_lista[17], atom_lista[18] = atom_lista[18], atom_lista[17]
atom_lista[26], atom_lista[27] = atom_lista[27], atom_lista[26]
atom_lista[51], atom_lista[52] = atom_lista[52], atom_lista[51]
atom_lista[89], atom_lista[90] = atom_lista[90], atom_lista[89]
atom_lista[91], atom_lista[92] = atom_lista[92], atom_lista[91]
atom_fil.close()
for i in range(len(atom_lista)):
atom_lista[i].number = i 1
return atom_lista
Code so far where I create a list consisting of the elements information. I have tried using the random.choice module but I don't really know how to get only the atomic symbol from the list with random.choice and also have the corresponding atomic number to the random atom be the correct answer.
CodePudding user response:
You can get the atomic symbol like this if you have the list of elements as you mentioned in the question.
import random
a=["1 H 1.0079", "2 He 4.0026", "3 Li 6.941", "4 Be 9.01218"]
random_choice = random.choice(a)
random_atom = random_choice.split(" ")[1]
print(random_atom)
CodePudding user response:
Try this. Clearly you could put it into a loop. I just used a part of your List.
import random
elements = ['1 H 1.0079', '2 He 4.0026', '3 Li 6.941', '4 Be 9.01218']
choose = random.choice(elements)
splitted = choose.split(' ')
print('The element symbol is : ', splitted[1])
attempt = input('Enter the Atomic Number ')
if (attempt == splitted[0]):
print('Correct')
else:
print('Wrong')