简体   繁体   中英

Python dice roll guessing game with user input using randint and that gives feedback if guess was right or wrong

I'm fairly new to Python and I'm trying to create a game where you simulate a 6 sided die roll. The user has to guess a number and the program should tell them if their guess was right or wrong. The problem I have run into is that my program always says the user guessed wrong even when they guessed correctly. I'm just not sure what the problem is. The issue persists no matter what sort of loop I use.

def main():
#importing random
import random
#creating random numbers 1-6 inclusive
roll = random.randint(1, 6)
print(roll)
#taking user input
user_guess = input("Guess a number between 1 and 6: ")
if user_guess == roll:
    print("You guessed correctly!")
    else:
    print("Better luck next time.")

main()

here the problem is the type of the variables. You are trying to compare a string(user_guess) with an int(roll).

You can convert the int to the string for instance by doing this:

if user_guess == str(roll):

Then it should work. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM