How can I generate an Integer number in python using Random

Asked

Viewed 136 times

-1

I have the following code and I need the result to be an integer type number, but it is returning a random value (number or None) with random type (int or nonetype)

from random import randint


def chave2():

    final = ((3-1)*(7-1))
    np = randint(2, final-1, 1) #Esta gerando tipos aleatórios para np
    cont = 0
    for x in range(1, np+1):
        if np % x == 0:
            cont += 1
    if cont == 2 and final % np != 0:
        return np
    else:
        chave2()

print(type(chave2()))

print(chave2())

ps:I have tried several Ides and different tmb versions, I am using version 3.7.4

  • randint takes 2 arguments randint(start, end) and not 3 !

1 answer

0

Along those lines np = randint(2, final-1, 1) the function randint should receive only 2 arguments, generating error during execution. Then it should be changed to np = randint(2, final-1), with only two arguments being passed. If the three arguments are really needed, you may want to use randrange(start, stop\[, step\]).

Another necessary thing is that you add one return to the Else declaration.

After the changes is:

from random import randint

def chave2():

  final = ((3-1)*(7-1))
  np = randint(2, final-1) #mudança
  print(np, final, 't', type(np))
  cont = 0
  for x in range(1, np+1):
    if np % x == 0:
      cont += 1
  if cont == 2 and final % np != 0:
      return np
  else:
    return chave2() # mudança

print(type(chave2()))

print(chave2())
  • Thank you, I was using the three arguments in a randrange function, but the changes worked

Browser other questions tagged

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