如何通过变量获取periodictable库中元素的mass属性?
Hey there! Let's sort out why your code isn't running and get it working properly.
The Problem with Your Original Code
Your current approach tries to use a user-input string directly as an attribute name with periodictable.Element.mass, but Python doesn't interpret the variable Element as the element you're targeting here. Instead, it's looking for an attribute literally named Element in the periodictable module—which doesn't exist, hence the error.
The Correct Approach
The periodictable library provides an elements dictionary that lets you look up elements by their symbol (like 'H') or full name (like 'hydrogen'). You can use this to fetch the correct element object, then access its mass property.
Here's a revised, working version of your function:
import periodictable def get_element_mass(): element_input = input("Element? ") try: # Look up the element using the input (works for symbols or full names) element = periodictable.elements[element_input] return element.mass except KeyError: # Handle cases where the input isn't a valid element print(f"Oops, '{element_input}' isn't a recognized element!") return None # Test the function print(get_element_mass())
Alternative: Using getattr()
If you prefer using attribute access (this only works for element symbols, not full names), you can use getattr() to dynamically fetch the element:
import periodictable def get_element_mass(): element_symbol = input("Element symbol? ") try: element = getattr(periodictable, element_symbol) return element.mass except AttributeError: print(f"Sorry, no element found with symbol '{element_symbol}'!") return None
Key Notes
- Always remember to import the
periodictablelibrary (your original code didn't show this import—don't forget it!) - Adding try/except blocks prevents your program from crashing if the user enters an invalid element name/symbol.
- The
elementsdictionary is more flexible because it accepts both symbols and full element names.
内容的提问来源于stack exchange,提问作者Matteo Bianchi

