variable creation
Justin Azoff
justin.azoff at gmail.com
Tue Aug 8 10:40:37 EDT 2006
Alistair King wrote:
> Hei all,
>
> im trying to create a list of variables for further use:
[snip]
> this works to a certain extent but gets stuck on some loop. Im a
> beginner and am not sure where im going wrong.
You are trying to do too much in one function. Split those loops up
into a few little ones and the program will work... or if it doesn't,
you'll know exactly where the problem is.
def get_element(pt):
"Return None or a single element from the periodic table"
while 1:
el = raw_input("Which element would you like to include? ")
if not el: #blank answer
return
if el in pt:
return pt[el]
print "This element is not in the periodic table, please try
again"
def get_elements(pt):
elements = []
while 1:
el = get_element(pt)
if not el:
break
elements.append(el)
return elements
See how using two separate functions makes it easy to test?
In [10]:print get_element(pt)
Which element would you like to include? X
This element is not in the periodic table, please try again
Which element would you like to include? H
1.0079400000000001
In [11]:print get_elements(pt)
Which element would you like to include? Z
This element is not in the periodic table, please try again
Which element would you like to include? Li
Which element would you like to include? B
Which element would you like to include? H
Which element would you like to include?
[6.9409999999999998, 10.811, 1.0079400000000001]
Now, since the information for a single element consists of more than
just a single number, you'll probably want to make a class for them.
Once you have an object for every element, you can add them to a class
for the periodic table.
--
- Justin
More information about the Python-list
mailing list