You need to create a variable as follows (pseudocode):

Имя_%номер-пользователя% = значение 

How to do this?

  • I did not understand the question? Could you write a more detailed question? And tell us more about the problem being solved, maybe you should just use a different approach - Viktorov

2 answers 2

In addition to the existing answer.

Dynamic variable creation is difficult to maintain. And it may not be safe.

You can use dictionaries. Dictionaries are keys and values ​​storages.

 >>> dct = {'x': 1, 'y': 2, 'z': 3} >>> dct {'y': 2, 'x': 1, 'z': 3} >>> dct["y"] 

You can also use key names as variables.

 >>> x = "spam" >>> z = {x: "eggs"} >>> z["spam"] 'eggs' 

For cases when you think of something like

 var1 = 'foo' var2 = 'bar' var3 = 'baz' ... 

the list may be more appropriate than the dictionary. The list is an ordered sequence of objects with integer indices:

 l = ['foo', 'bar', 'baz'] print(l[1]) # prints bar, because indices start at 0 l.append('potatoes') # l is now ['foo', 'bar', 'baz', 'potatoes'] 

Lists can be more convenient than dictionaries with whole keys. For example, adding and deleting items is more convenient.

    For example:

     import os uid = os.getuid() print(uid) # 1000 try: print(name_1000) except NameError as e: print(e) # name 'name_1000' is not defined locals()[f'name_{uid}'] = 42 print(name_1000) # 42 

    But we must remember that the dynamic creation of variables is a very bad practice. Most likely, our plans should be implemented through associative data structures (dictionary, for example).

    Depending on the task, the variable can be created not only in the local, but also in the global scope using the globals function.

    • one
      Or globals()[...] = ... - gil9red
    • @ gil9red, thanks, updated answer - mkkik