Hi! On school we got exercise to calculate how much the length of substance grow when we know original length and temperature change.
So,the case goes that i have value temperature coefficient of different substances and i have to multiply them. I'd like to it without doing several condition statements. I tried to do a class and function but it didn't work out.

Here's the code, and i don't have any clue how to finish it. It should calculate
like aluminium*1meter*1celsius and print out answer without using condition statements, but is there a way to do it?

``````#-*- coding: cp1252 -*-
aluminium = 0.000023
concrete = 0.000012
silver = 0.000019
gold = 0.000014
copper = 0.000017
glass = 0.000008

a = raw_input("enter substance: ")
l = float(raw_input("give original length: "))
t = float(raw_input("how much the temperature changes: "))

print'length changes', l, 'meters'``````

I would instead of using seperate variables for the different materials, use a dictionary

``````#-*- coding: cp1252 -*-
substances = {
'aluminium':0.000023,
'concrete':0.000012,
'silver':0.000019,
'gold':0.000014,
'copper':0.000017,
'glass':0.000008,
}

a = raw_input("enter substance: ")
l = float(raw_input("give original length: "))
t = float(raw_input("how much the temperature changes: "))

be aware that it will be case sensitive and Aluminium won't be recognised whereas aluminium is

There are several ways to do this. First, you might want to use a menu, with a number input, instead of keying in "aluminium", etc. as they can be spelled differently (aluminum). Then use a dictionary or list of lists to chain the values to the raw material.

``````material_dict = {"concrete" : 0.000012,
"silver" : 0.000019,
"gold" : 0.000014 }     ## etc
# or
material_list = [ ["concrete", 0.000012], \
["silver", 0.000019], \
["gold", 0.000014] ]``````

Making it using dictionary seemed simpler to me (used it once). But thanks guys, i really appreciate ur help.

Generally speaking, a dictionary should be used instead of several if/elif/else statements. It is easier to read and understand, and easier to modify since entries can be added or deleted from the dictionary. You will probably use dictionaries quite often so try to become more familiar with the object over time.

commented: agree +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.