I am looking for a piece of code that takes a list of redshifts (i.e. numbers) as input from the user, separated by spaces and in one go, and then automatically assigns them to variables like a,b,c,d.....m,n,o.
For example, if the user gives "0.32 0.53 0.77 0.91 1.1 1.4" as an input, the program should assign 0.32 to variable a, 0.53 to variable b, 0.77 to variable c, and so on. I do not expect the user to input more than 10 numbers.
I have been trying to the best of my knowledge to use the raw_input function for this, but to no success thus far.
Following this I am planning to use the simple formula A=3800/(1+a)
to find the shortest rest-frame wavelength that a body at redshift "a" would be seen to emit in the optical range, and repeat this process for all the other bodies whose redshifts have been given by the user. This part should present no problem however. My real stumbling block is as described above.
Let's say that you got a string from a user using raw_input()
:
astr = raw_input('Input: ')
Then, there are many ways you can handle this. But the easiest might be to just split that string into a list:
alist = astr.split(' ') # returns ['0.32', '0.53', '0.77', '0.91', '1.1', '1.4']
Since you probably want them to be floats instead of string, you can use a list comprehension:
alist = [float(val) for val in astr.split(' ')] # returns [0.32, 0.53, 0.77, 0.91, 1.1, 1.4]
You can also put it all in a dictionary:
dic = {j:float(val) for j, val in enumerate(astr.split(' '))}
If you want to name them by letters and if you are sure there will be less than 26, you can do this:
from string import ascii_lowercase as letters
dic = {letters[j]:float(val) for j, val in enumerate(astr.split(' '))}
Finally, you could use exec
but that's very bad form and I would not recommend it.