How can I do the following in python;
for i in range(4):
s_i = 3
so I get
s_0 = 3
s_1 = 3
s_2 = 3
s_3 = 3
Keep data out of your variable names. If you want numbered variables, you really need a list:
s = [3] * 4
Then you can access elements with indexing notation:
s[2] = 5
instead of trying to build variable names dynamically.
If you want more general dynamically-named variables, like variables whose names come from user input, you really need a dict:
parents = {}
for i in xrange(5):
child = raw_input('Enter child name:')
parent = raw_input('Enter parent name:')
parents[child] = parent
I didn't get your question exactly. But I have tried this:
for i in range(4):
exec('s_'+str(i) + '=i')
Out Put :
s_0 = 0
s_1 = 1
s_2 = 2
s_3 = 3
on the fly we are creating 4 variables and assigning values to it.
While the following works, it seems like a very, very bad idea:
>>> for j in range(4):
... globals()['s_{}'.format(j)] = 3
...
>>> s_0
3
>>> s_1
3
>>> s_2
3
>>> s_3
3
EDIT Replaced locals()
with globals()
. According to the docs for locals()
:
The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.