-2
votes

How can i create dynamic variables in Python with the name of the user? For example there is a user "John", so i will to create some variables with the name "John", such as variables john1,john2,john3.

1
Why not use a dictionary? What namespace are your variables supposed to be defined in? - Martijn Pieters♦
does python have arrays? - Sam I am says Reinstate Monica

1 Answers

3
votes

Quite easy, but probably not desirable. I would look at your design again and consider if a dictionary might be a better way forward.

However, since you asked the question, you can use the exec bultin:

var  = 'John1'
value = 42

exec "%s = %d" % (var,value)
exec "print %s" % (var)

print (dir())

gives:

42
['John1', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'value', 'var']

(Python 2.7.3)

Edit: @BrianOakley's comment has a point. Using mechanisms like this is a bit like drinking alcohol. Seems a good idea at the time and temporarily solves your problems, but you know you will regret it in the morning. Long term it just causes more grief, and you know your mother would not like you doing it.