3

Basically I'm trying to make a little program using the periodic table library and I tried to make the first function which returns the mass of the given element.

def mass():
    Element = input("Element?   ")
    return periodictable.Element.mass

But this doesn't work because I'm trying to use a variable instead of an attribute so it says this:

Traceback (most recent call last):
File "<string>", line 424, in run_nodebug
File "<module1>", line 25, in <module>
File "<module1>", line 22, in main
File "<module1>", line 15, in mass
AttributeError: module 'periodictable' has no attribute 'Element'

The correct way to use the mass function with the periodic table should be this:

print(periodictable.H.mass)
print(periodictable.O.mass)
print(periodictable.Na.mass)

So what I'm asking is: can I give an attribute with a variable or do you have any other solution to make the user choose the element?

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
Matteo Bianchi
  • 113
  • 1
  • 7
  • 3
    Check out [`getattr`](https://docs.python.org/3.5/library/functions.html#getattr). – bla May 05 '18 at 14:10

2 Answers2

4

The module seems to have a function for this:

periodictable.elements.symbol(Element).mass

This help page might be useful if you also need to access elements by name etc.:

help(periodictable.elements)

The general method for this sort of thing is using getattr:

getattr(periodictable, Element).mass

But this will also find other attributes of "periodictable", like the functions it defines and so on, so it's better to avoid it for this kind of application where you're looking up something typed by the user of your program.

snowcat
  • 284
  • 1
  • 5
1

You can use getattr:

>>> import periodictable
>>> periodictable.Na.mass
22.98977
>>> element = 'Na'
>>> getattr(periodictable, element).mass
22.98977
bla
  • 1,840
  • 1
  • 13
  • 17