You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过变量获取periodictable库中元素的mass属性?

Fixing Your Periodictable Element Mass Function

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 periodictable library (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 elements dictionary is more flexible because it accepts both symbols and full element names.

内容的提问来源于stack exchange,提问作者Matteo Bianchi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:26:28