How do I get a random number to link with my specific number?

45 views Asked by At

Im trying code a simple dice roll game where the player is to roll a dice and they try to get it to land on a specific number to win. How do I get it to print “you won” when it lands on this number?

I tried save the secret number as a string in the variable total. I then tried to do an if statement where if int is equal to total, then it would print “you won”

2

There are 2 answers

0
SokolovVadim On

I assume the problem is in comparison between number and a string. Since you are generating a number, you need to compare it to a number, not a string. And then print the result if it equals to your secret number.

secret_num = 5

generated_num = randint(1, 6)
if generated_num == secret_num:
    print('You won')

0
JCTL On

If the secret number is a string type, you can cast the dice roll result into a string to be compared (or you can have both as int, as long as both of them are the same type). To print “you won”, a simple if-else statement is sufficient:

import random

# Set the secret number (string)
secret_number = "1"

# Simulate the user rolling the dice
guess = str(random.randint(1, 6))
print("You rolled:", guess)

# Check if the player won
if secret_number == guess:
    print("You won!")
else:
    print("Sorry, you lost. Try again.")

Another demo for both secret number and guess being integer:

import random

# Set the secret number (int)
secret_number = 1

# Simulate the user rolling the dice
guess = (random.randint(1, 6))
print("You rolled:", guess)

# Check if the player won
if secret_number == guess:
    print("You won!")
else:
    print("Sorry, you lost. Try again.")