First, the error is because you are trying to make an assignment to a literal, in this case an integer. You try to define a variable called 1
and assign the reference to an object. This is not possible, moreover, an identifier (variable name) can not be a number as is logical, but neither can it start with one ( 1a = "Hola"
for example is invalid syntax).
In addition to this, string literals must always be enclosed in quotation marks, otherwise they will be interpreted as an identifier and not as a string:
>>> s = hola # Error si hola no está definido
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'hola' is not defined
>>> s = "hola" # Correcto
>>> hola = 14
>>> s = hola # Asigna a s la referencia al objeto asociada a la variable hola
>>> s
14
That said, for what you want the appropriate thing is to use a container, for example:
-
A list / tuple and indexed:
import random
opciones = ("pedro", "maria", "juan", "luis")
opc = opciones[random.randrange(0, 4)]
print(opc)
-
A dictionary:
import random
opciones = {1: "pedro", 2: "maria", 3: "juan", 4: "luis")
opc = opciones[random.randrange(1, 5)]
print(opc)
We can directly use random.choice
that gets an item randomly (pseudo-randomly) of a sequence:
import random
opciones = ("pedro", "maria", "juan", "luis")
opc = random.choice(opciones)
print(opc)
If you do not want to use an iterable one, we can still do something. In line with your original idea, what you apparently wanted was to choose randomly based on its name from a series of variables previously defined and associated with chains. This is possible using eval
, although it is not appropriate or recommended as a general rule. Obviously, as already explained, the variables can not be a number:
import random
v1 = "pedro"
v2 = "maria"
v3 = "juan"
v4 = "luis"
opc = eval(f"v{random.randrange(1, 5)}")
print(opc)
eval
accepts a string that must be valid Python code, evaluates it and returns the result of its evaluation. In this case, it receives a string that represents an identifier ( "v1"
, "v2"
, "v3"
or "v4"
) and returns the object associated with it, the string with the name.
A string literal is used to generalize the statement. The formatted string literals are available from Python 3.6, it can be used alternatively for example:
opc = eval("v{}".format(random.randrange(1, 5)))
or:
opc = eval("v" + str(random.randrange(1, 5)))
Note: random.randint
is really just an alias for random.randrange(start, stop+1)
, so its only difference with randrange
(apart from not accepting the third parameter, step
) is that the stop
parameter is included among the possible options:
-
random.randrange(1, 5)
- > An integer in the interval 1 < = n < 5. Does not include 5.
-
random.randint(1, 5)
- > An integer in the interval 1 < = n < = 5. The 5 is included.