Error with Random function

Asked

Viewed 165 times

1

This is the code I wrote in Python:

from random import randint

a = randint

print(a)

When using the function randint in this simple code, the console gives me the following error:

<bound method Random.randint of <random.Random object at 0x0000015E1A1D4FD0>>

3 answers

2

That’s what you get is not a mistake! This is the literal value of your function that you get through the code below:

>>> v = randint.__str__() # Devolve uma string
>>> print("\n" + v)

<bound method Random.randint of <random.Random object at 0x0000015E1A1D4FD0>>

There are two problems with your code. The first problem is that you didn’t call the function. To call a function, use the parentheses (open and close parentheses) as in the example below:

var = func()

The second problem of your code, is that you did not pass the necessary arguments to call the function randint().

To perform this function, you must pass an initial value and a final value. Thus, the randint will return a random value between a and b, example:

x = randint(0, 3) # Retorna um valor entre 0 e 3

What you were doing in your code was assigning the function randint to the variable a, making both functions the same. Example:

a = randint
a is randint # True

randint(0, 3)
a(0, 3) # Posso executá-la assim como no randint já que ambos são idênticos.

1

That value:

<bound method Random.randint of <random.Random object at 0x0000015E1A1D4FD0>>

It is not an error, it is the literal value of the function randint.


Notice that you imported the function randint of random but did not invoke the same, just displayed it on the console.

See, I can do this with other functions, printing its literal value:

print(print)

Even, I could use the value present in the variable a to invoke the function, see this example:

from random import randint

#A variável a agora contém a função randint
a = randint

#A variável b agora contém a função print
b = print

#Logo eu posso chamar a randint pela variável a
c = a(1,3)

#E exibir no console(print) com a variável b
b(c)

Online example: https://repl.it/repls/PeacefulFriendlyMeasurements


If you want to make use of the randint function, you need to open the parentheses and enter the required parameters:

from random import randint

a = randint(1,2)

print(a)

See these examples online: https://repl.it/repls/MediumRealisticDisc

Documentation of the Ring: https://docs.python.org/3/library/random.html

-2

You’re misusing the function. example:

from random import randint
a = randint(1, 10)
print(a)

The range is missing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.