Search This Blog

Sunday, January 9, 2011

Dictionary example

#program to determine resistance of a resistor using colour bands--uses dictionary
color1={'black':0,'brown':1,'red':2,'orange':3,\
       'yellow':4, 'green':5,'blue':6,'violet':7,\
       'gray':8,'white':9}
color2={'black':1e0,'brown':1e1,'red':1e2,'orange':1e3,\
       'yellow':1e4, 'green':1e5,'blue':1e6,'violet':1e7,\
       'gray':1e8,'white':1e9,'gold':1e-1,'silver':1e-2}
color3={'brown':1,'red':2,'green':0.5,'blue':0.25,\
        'violet':0.1,'gray':0.05,'gold':5,'silver':10,'none':20}
resist=0
while 1:
    b1=str(raw_input("Enter colour first band = ")).lower()
    if b1 in color1:
        resist=color1[b1]
        break
    else:
        print "Enter a valid color"
        continue
   
resist *=10
while 1:
    b2=str(raw_input("Enter colour second band = ")).lower()
    if b2 in color1:
        resist +=color1[b2]
        break
    else:
        print "Enter a valid color"
        continue

while 1:
    b3=str(raw_input("Enter colour third band = ")).lower()
    if b3 in color2:
        resist *=color2[b3]
        break
    else:
        print "Enter a valid color"
        continue

while 1:
    b4=str(raw_input("Enter colour fourth band = ")).lower()
    if b4 in color3:
        tol=color3[b4]
        break
    else:
        print "Enter a valid color"
        continue


print resist," +-",tol,"%"


      

No comments:

Post a Comment