Is there any way to generate a number of raw_inputs (With unique variables) based on user input? So, say I had this:
if choice == 1:
noelemen = int(raw_input("Enter total amount of elements: "))
Would there be any way to make it so the integer put in that raw_input field would then “generate” the required amount of raw_inputs? I’d suppose, if it was possible, that it’d make use of functions or something similar, but I’m a bit confused about how I’d get it done to be able to do that.
What I have currently is this:
if noelemen == 1:
first = raw_input("Enter element: ")
#Look for the weight of the entered element
weight1 = float(elemen_data.get(first.lower()))
if weight1 is not None:
total_weight = weight1
print "Total mass =", total_weight
if noelemen == 2:
first = raw_input("Enter first element: ")
second = raw_input("Enter second element: ")
#Look for the weight of the entered element
weight1 = float(elemen_data.get(first.lower()))
weight2 = float(elemen_data.get(second.lower()))
if weight1 is not None:
total_weight = weight1 + weight2
print "Total mass =", total_weight
Which is probably a pretty messy way of doing it, particularly as I’d have to go up to perhaps something like 10 elements, or perhaps even beyond.
So, to repeat… Any way to generate raw_inputs with unique variables based on user input?
how about something like this?
Example case:
at this point, the value of the variable
numberOfPromptswill be2.The value of the variable
elementswill be[], i.e. it is an empty listnumberOfPromptsstays2,elementswill be['3.1415']elementswill be['3.1415', '2.7182']Now the for-loop is done and you got your user inputs conveniently in the 0-indexed list
elements, which you access like a tuple (array):Edit:
After reading your comment I noticed what you intend to do and, just like the other answer stated, it would be best to use a dictionary for this. This should work:
now
elementswill look like this:you can iterate over all keys like this (to find out, which elements have been entered):
To get all values (to sum them up, for instance), do something like this:
Keep in mind that this example is for python 2.x. For python 3.x you will need to adjust a couple of things.