problem with Random.radint(1, 6) and if conditional

Asked

Viewed 65 times

3

Friends, I am starting out in programming, so I apologize if it is too banal my question. My guess is that something happens in the if string, because never the winning message is read, the program always reads the "Try Again', and that’s right if the number.

Could someone throw a light please?

import random

dada = random.randint(1, 6)

guess = input('Make a choice between the numbers: 1 and 6: ')

if dada == guess:
    print('Congratulations! You won!')
else:
    print('Try again.')

print('You selected the number {} and the number {} was sorted.'.format(guess, dada))

print("Let's play again!")

1 answer

5


Victor,

This is happening because of the types of variables.

Its variable dada is a whole (int), return of the randint method, but the variable guess is a string (str), because the input function returns a text.

To fix this situation, you can convert the return of the input function to an integer, with the int function, example:

guess = int(input('Make a choice between the numbers: 1 and 6: '))

So your code would look more or less like this:

import random

dada = random.randint(1, 6)

guess = int(input('Make a choice between the numbers: 1 and 6: '))

if dada == guess:
    print('Congratulations! You won!')
else:
    print('Try again.')

print('You selected the number {} and the number {} was sorted.'.format(guess, dada))

print("Let's play again!")
  • Thank you Daniel Mendes, it sure helped. Get mad about it here since yesterday, but what a silly mistake. But well, I think it’s just like that in the beginning. Thanks again.

Browser other questions tagged

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