[Tutor] Help
Alan Gauld
alan.gauld at btinternet.com
Sat Mar 7 20:04:55 CET 2015
On 07/03/15 15:39, elie khairallah wrote:
> hello , I would like to know if theres a way to change a variable's name
> after every iteration for example I want to make a function that stores a
> number in x_1 if i=1 and in x_2 if i=2.
> To be more precise:
> i=1
> def f(n):
> while i<n:
> x_i = i**2 ##this writing is wrong I would like here to have
> x_1 or x_2 ...
> (depending on i)
> return (x_1,x_2,x_3 .....)
Others have already suggested a list, which IMHO is the best option.
However if for some reason the zero based index of a list is an
issue for you then you could use your naming scheme in a
dictionary:
def f(n):
values = {}
root = 'x_'
for n in range(1,n+1):
values[root+str(n)] = n**2
return values
You can then access the values with, for example:
print (values['x_2'])
But unless you are reading the variable names from
a file/network or a user then the numerical index of a
list will usually be easier to work with.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list