Function randint does not return a value

Asked

Viewed 34 times

0

I wanted to make the randint call a random number, save the value of that number, open a question to the user and if; the user’s answer is equal to the number, say that he hit, if different, say he missed. However, in the code I did is always saying it’s wrong. follow the code

def adivinharnumero():
  from random import randint
  numeroaleatorio=randint(0,1)
  print(numeroaleatorio)
  resposta=input("Adivinhe o valor aleatório")
  print(resposta)
  print(numeroaleatorio)
  if resposta==numeroaleatorio:
    print("parabéns, você acertou!!!")
  if resposta!=numeroaleatorio:
    print("você errou")

adivinharnumero()

1 answer

1


This is happening because of the types of variables numeroaleatorio and resposta.

When you ask the user for the number, you use the function input, which returns a string, but you compare it to the return of the function randint, that returns an integer... Soon this data will always be different.


You can fix it very simply by converting the value informed by the user to integer, using the function int:

resposta = int(input("Adivinhe o valor aleatório: "))

It is also possible to do the inverse, transform the value returned by randint in a string, using the function str:

numeroaleatorio = str(randint(0,1))

Documentations:

https://docs.python.org/3/library/functions.html#input

https://docs.python.org/3/library/functions.html#func-str

https://docs.python.org/3/library/functions.html#int

  • 1

    Valew man! You’re a beast!!!!!

Browser other questions tagged

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