Search code examples
pythonfunctionclasspython-2.xraw-input

How do I use raw_input with classes in a definition


Problem

I'm writing a script in Python 2.7 that has the user input the atomic symbol for an element. The script then prints out information about the element.

However, I'm not sure how to have a class use a variable from the raw_input. Here is the code with a couple of the 118 elements gone for readability:

Code

class PTable(object):
    def __init__(self, name, atom_num, atom_sym, atom_mass,period, group, atom_type,state):
        self.name = name
        self.atom_num = atom_num
        self.atom_sym = atom_sym
        self.atom_mass = atom_mass
        self.period = period
        self.group = group
        self.atom_type = atom_type
        self.state = state

h = PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas")
he = PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas")
li = PTable("Lithium",3,"Li",6.941,2,1,"Alkali metal","Solid")
be = PTable("Beryllium",4,"Be",9.0121831,2,2,"Alkaline earth","solid")
og = PTable("Oganesson",1,"H",1.008,1,1,"Nonmetal","Gas")

def results(name, num, sym, mass, per, gro, typ, state):
    print "Name:", name
    print "Atomic number:", num
    print "Atomic symbol:", sym
    print "Atomic mass:", mass
    print "Period:", per
    print "Group:", gro
    print "Type:", typ
    print "State:", state
# results(h.name, h.atom_num, h.atom_sym, h.atom_mass, h.period, h.group, h.atom_type, h.state)
def hub():
    x = raw_input("What element? ")
    results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x)
    hub()

hub()

Errors

The code that gives me the syntax error is:

results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x)

The error is obvious; syntax is wrong, so I tried another way:

results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state)

That, too, did not work, and I got the error

Traceback (most recent call last):

File "C:/Users/NAME/Desktop/PTable.py", line 146, in

hub()

File "C:/Users/NAME/Desktop/PTable.py", line 143, in hub

results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state)

AttributeError: 'str' object has no attribute 'name'

Question

Do you know how I can make it so the user is able to type in the name of the element (the atomic symbol) and the code prints out the information?


Solution

  • Recovering an element

    The line x = raw_input("What element? ") provides you with a string, say 'he', so when you call x.name you are attempting to access an attribute of that string and not of the variable he.

    What you should do is store your elements in a dictionary instead of having them as variables and access them with the key provided by your user.

    periodic_table = {
        'h': PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas"),
        'he': PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas"),
        ...
    }
    
    symbol = raw_input("What element? ")
    
    try:
        element = periodic_table[symbol]
    
    except KeyError:
        print('This element does not exist')
    

    Printing the element

    As for printing the element, I would suggest a more object-oriented approach by implementing the PTable.__str__ method.

    class PTable(object):
    
        ...
    
        def __str__(self):
            # Add in the format and information that you want to be printed
            return "Name: {}".format(self.name)
    

    You can then directly print your elements.

    print periodic_table['he']
    # prints: 'Name: Helium'