mardi 29 décembre 2020

Is it possible to loop through several variables that have range values?

Super newb here. I'm doing a python challenge on 101computin.net and I can't figure out how to make my code shorter. I have tried placing these variables into a list, but then I can't check if density is in the range within the list because object can't be interpreted as an integer.

#Eureka! - Archimedes and King Hiero's Crown - www.101computing.net/eureka-and-king-hieros-crown/
mass = float(input("Input the mass of the crown in kg"))
volume = float(input("Input the volume of the crown in cubic meter"))

density = mass / volume

aluminum = range(2400, 2700)
bronze = range(8100, 8300)
silver = range(10400, 10600)
lead = range(11200, 11400)
gold = range(17100, 17500)
platinum = range(21000, 21500)

if density in Aluminum:
    print('Your crown is aluminum!')
elif density in bronze:
    print('B')
elif density in silver:
    print('S')
elif density in lead:
    print('L')
elif density in gold:
    print('G')
elif density in platinum:
    print('P')
else:
    print('Nope!')

Obviously all the if/elif statements will work, but is there an easier way to loop through the ranges and determine which metal the output is based on the density?

Aucun commentaire:

Enregistrer un commentaire