Reputation: 21
I want to create multiple variables based on a number that I have defined.
Currently, I have a client and a server running and every time a client joins, I want the server to create a variable. Each user is assigned a number:
list_of_addr = []
user_num = 0
recv_verf, addr = server_socket.recvfrom(2048)
if(recv_verf == 'connect'):
recv_user, addr = server_socket.recvfrom(2048)
list_of_addr.append('User:' + recv_user + ' # ' + str(user_num) + '\n')
user_num = user_num + 1
print 'User:' + recv_user + ' # ' + str(user_num) + ' connected'
I want a variable to be created here based on this number. Similar to user_(user_num) = 0.
I don't know how else to explain this. Sorry is this is vague.
Upvotes: 0
Views: 190
Reputation: 718
A dict would be an appropriate solution for this :
list_of_addr = []
user_num = 0
recv_verf, addr = server_socket.recvfrom(2048)
if(recv_verf == 'connect'):
recv_user, addr = server_socket.recvfrom(2048)
list_of_addr.append(dict(user=recv_user, number=user_num))
user_num = user_num + 1
print 'User: {0} # {1} connected'.format(list_of_addr[-1]['user'], list_of_addr[-1]['number']
Upvotes: 0
Reputation: 527043
Don't do this. If you want to have a dynamic group of items pointed to by names, that's what a dict
is for. If you just want an list of items in a particular order, that's what a list
is for.
Variable names should be kept to what you, the programmer, actually write in your code. Down the other path lies madness.
Upvotes: 9