How to Create a Element info using Python

I’m excited to share a Python project I’ve been working on that retrieves detailed information about chemical elements from the periodic table. This tool goes beyond just the name and atomic number; it fetches properties like electronegativity, atomic radius, and even phase at standard conditions all thanks to the excellent periodictable library. In this post, I’ll walk you through the code, explain the new features, and wrap up with some final thoughts on how you can extend it further.

Why I Built This Tool

I’ve always found the periodic table fascinating, but I wanted a quick, interactive way to look up properties of elements without having to browse multiple web pages. The periodictable Python library offers a rich dataset, so I decided to create a command-line tool that’s both user-friendly and comprehensive.

Key Features and Improvements

  1. Enhanced Property Retrieval
    • I’ve included 12 different properties such as group, period, phase, density, melting point, boiling point, and electronegativity.
    • Missing properties are automatically handled, so the tool won’t crash if an element doesn’t have a particular attribute.
    • Numerical values are formatted for clarity (e.g., 4 decimals for atomic mass, 2 decimals for density).
  2. Flexible Input Handling
    • The program accepts both element symbols (case-insensitive) and atomic numbers.
    • A built-in help command (help) lists all available elements by atomic number, symbol, and name.
    • The script continues running until you type quit or exit.
  3. Improved Output Formatting
    • Properties are neatly aligned for better readability.
    • Error messages are clear, explaining exactly why the input wasn’t valid.
  4. Error Handling
    • The code gracefully handles invalid inputs (e.g., typing in “abc” or an out-of-range atomic number).
    • Helpful suggestions prompt you to use the help command or correct your input.
  5. Modular Code Structure
    • Functions are separated for maintainability (get_element_info, display_element_info, element_lookup).
    • Each function has a docstring explaining its purpose.

The Code

Below is the complete Python script. Before running it, ensure you have installed the periodictable library:

pip install periodictable
import periodictable

def get_element_info(element):
"""Retrieve comprehensive information about an element."""
properties = [
("Name", "name"),
("Symbol", "symbol"),
("Atomic Number", "number"),
("Atomic Mass", "mass"),
("Group", "group"),
("Period", "period"),
("Phase", "phase"),
("Density (g/cm³)", "density"),
("Melting Point (K)", "melting_point"),
("Boiling Point (K)", "boiling_point"),
("Electron Configuration", "electronic_configuration"),
("Atomic Radius (pm)", "atomic_radius"),
("Electronegativity", "electronegativity"),
]

info = {}
for label, attr in properties:
value = getattr(element, attr, None)
if value is not None:
# Format numerical values
if isinstance(value, float):
if "Atomic Mass" in label:
value = f"{value:.4f}"
else:
value = f"{value:.2f}"
info[label] = value
return info

def display_element_info(info):
"""Display element information in a formatted way."""
if not info:
print("Element not found. Please check your input.")
return

max_key_length = max(len(key) for key in info.keys())
for key, value in info.items():
print(f"{key.ljust(max_key_length)} : {value}")

def element_lookup():
"""Main function to handle user interaction."""
print("Element Information Lookup")
print("Enter 'help' for element list | 'quit' to exit\n")

while True:
user_input = input("Enter element symbol/number: ").strip()

if user_input.lower() in ('quit', 'exit'):
break

if user_input.lower() == 'help':
print("\nAvailable Elements:")
for el in periodictable.elements[1:]:
print(f"{el.number:3} {el.symbol:2} - {el.name}")
print()
continue

try:
# Try to get by atomic number
if user_input.isdigit():
atomic_number = int(user_input)
element = periodictable.elements[atomic_number]
else:
# Get by symbol
symbol = user_input.capitalize()
element = getattr(periodictable, symbol, None)

if element is None:
raise ValueError()

info = get_element_info(element)
print("\nElement Properties:")
display_element_info(info)
print()

except (ValueError, IndexError, AttributeError):
print(f"Error: '{user_input}' is not a valid element symbol or atomic number\n")

if __name__ == "__main__":
element_lookup()

How It Works

  1. Importing periodictable
    • I use this library to get all the elemental data.
  2. get_element_info(element)
    • A property list maps user-friendly labels (e.g., “Atomic Number”) to the actual attributes in periodictable.
    • Numerical values are formatted for readability.
    • Returns a dictionary of properties.
  3. display_element_info(info)
    • Takes the dictionary from get_element_info and neatly prints each key-value pair.
    • Aligns the text for a cleaner look.
  4. element_lookup()
    • Provides an interactive prompt.
    • Accepts numeric input (atomic number) or symbolic input (element symbol).
    • Handles special commands like help (to list all elements) and quit/exit (to leave the program).
    • Calls get_element_info and display_element_info to show results.

Example Usage

Here’s a sample interaction to demonstrate the tool:

Element Information Lookup
Enter 'help' for element list | 'quit' to exit

Enter element symbol/number: 17

Element Properties:
Name : Chlorine
Symbol : Cl
Atomic Number : 17
Atomic Mass : 35.4530
Group : 17
Period : 3
Phase : gas
Density (g/cm³) : 0.00
Melting Point (K) : 172.16
Boiling Point (K) : 238.55
Electron Configuration : [Ne] 3s2 3p5
Atomic Radius (pm) : 79.00
Electronegativity : 3.16

Adding More Properties

If you want to display additional properties (like isotopes, specific heat, or anything else periodictable supports), just:

  • Check the periodictable documentation for available attributes.
  • Add another tuple in the properties list inside get_element_info, for example:
("Specific Heat (J/g·K)", "specific_heat")
  • Make sure to handle any special formatting if needed.

Final Thoughts

I’m really proud of how this project turned out. By structuring the code into separate functions and including clear docstrings, it’s now easier to maintain and extend. The interactive help system and flexible input handling make it user-friendly for both beginners and advanced users who just need quick elemental data.

I encourage you to customize this script for your own needs maybe integrate it into a web application, or even build a GUI. The periodictable library is rich with data, so there’s a lot of room for creativity. If you have any ideas or improvements, feel free to share them!

Related blog posts