How to Create an Atomic Element Information Program in Python

When I first started working with Python, I was fascinated by how simple yet powerful it is for creating practical applications. One project that stands out is a program to fetch details about chemical elements using their atomic number, symbol, or name. I started with a basic version of the program, but as I progressed, I realized how it could be enhanced to make it more robust and user-friendly.

Project Overview

The goal of this project is to fetch and display details of a chemical element using the periodictable Python library. Users can search by atomic number, symbol, or name. The program also includes robust error handling and an interactive menu, making it more practical for real-world use.

Enhancements

Here are the key enhancements I added to the basic program:

  1. Input Validation: Ensures the user enters valid data.
  2. Exception Handling: Prevents crashes by managing invalid inputs gracefully.
  3. Flexible Search Options: Allows searching by atomic number, symbol, or name.
  4. Interactive Menu: Lets users query multiple elements without restarting the program.
  5. Graceful Exit: Provides a user-friendly option to exit the program.

Coding Structure

Below is the complete code for the enhanced version of the program:

import periodictable

def get_element_details_by_atomic_number(atomic_no):
    try:
        element = periodictable.elements[atomic_no]
        print(f"\nDetails for Atomic Number {atomic_no}:")
        print(f"Atomic number: {element.number}")
        print(f"Symbol: {element.symbol}")
        print(f"Name: {element.name}")
        print(f"Atomic mass: {element.mass}")
        print(f"Density: {element.density}\n")
    except KeyError:
        print(f"Error: No element found with atomic number {atomic_no}.\n")

def get_element_details_by_symbol(symbol):
    try:
        element = periodictable.elements.symbol(symbol.capitalize())
        print(f"\nDetails for Symbol '{symbol}':")
        print(f"Atomic number: {element.number}")
        print(f"Symbol: {element.symbol}")
        print(f"Name: {element.name}")
        print(f"Atomic mass: {element.mass}")
        print(f"Density: {element.density}\n")
    except KeyError:
        print(f"Error: No element found with symbol '{symbol}'.\n")

def get_element_details_by_name(name):
    try:
        element = periodictable.elements.name(name.capitalize())
        print(f"\nDetails for Name '{name}':")
        print(f"Atomic number: {element.number}")
        print(f"Symbol: {element.symbol}")
        print(f"Name: {element.name}")
        print(f"Atomic mass: {element.mass}")
        print(f"Density: {element.density}\n")
    except KeyError:
        print(f"Error: No element found with name '{name}'.\n")

def main():
    while True:
        print("Choose an option:")
        print("1. Get element details by atomic number")
        print("2. Get element details by symbol")
        print("3. Get element details by name")
        print("4. Exit")
        
        choice = input("Enter your choice (1/2/3/4): ")
        
        if choice == '1':
            try:
                atomic_no = int(input("Enter Element Atomic Number: "))
                get_element_details_by_atomic_number(atomic_no)
            except ValueError:
                print("Invalid input. Please enter a valid number.\n")
        elif choice == '2':
            symbol = input("Enter Element Symbol: ")
            get_element_details_by_symbol(symbol)
        elif choice == '3':
            name = input("Enter Element Name: ")
            get_element_details_by_name(name)
        elif choice == '4':
            print("Exiting program. Goodbye!")
            break
        else:
            print("Invalid choice. Please select a valid option.\n")

if __name__ == "__main__":
    main()

Features Added

Let me explain the features in detail:

  1. Flexible Search:
    • Users can search by atomic number, symbol, or name, making the program highly versatile.
  2. Validation:
    • Invalid inputs (e.g., non-numeric atomic numbers or unknown symbols) are handled gracefully with error messages.
  3. Exception Handling:
    • The program won’t crash even if the user enters invalid data, thanks to try-except blocks.
  4. Interactive Loop:
    • Users can query multiple elements in a single session, improving usability.
  5. Graceful Exit:
    • A clear exit option ensures the program closes smoothly.

Sample Run

Here’s how the program works:

Choose an option:
1. Get element details by atomic number
2. Get element details by symbol
3. Get element details by name
4. Exit
Enter your choice (1/2/3/4): 1
Enter Element Atomic Number: 11

Details for Atomic Number 11:
Atomic number: 11
Symbol: Na
Name: sodium
Atomic mass: 22.98977
Density: 0.971

Choose an option:
1. Get element details by atomic number
2. Get element details by symbol
3. Get element details by name
4. Exit
Enter your choice (1/2/3/4): 2
Enter Element Symbol: He

Details for Symbol 'He':
Atomic number: 2
Symbol: He
Name: helium
Atomic mass: 4.002602
Density: 0.0001786

Choose an option:
1. Get element details by atomic number
2. Get element details by symbol
3. Get element details by name
4. Exit
Enter your choice (1/2/3/4): 4
Exiting program. Goodbye!

Why This Project Matters

This project is a great way to explore Python’s flexibility and learn how to work with external libraries like periodictable. It’s also a practical tool for students, educators, or anyone interested in chemistry. Moreover, the enhancements make it a polished and professional-grade application.

Conclusion

I thoroughly enjoyed creating and enhancing this project. It was an excellent exercise in coding, problem-solving, and adding user-friendly features. If you’re looking to sharpen your Python skills, I encourage you to try this project and add your own enhancements.

Related blog posts