-2

Can someone shed some light on what I'm doing wrong with my code? I'm using Python 3.6. And a beginner. Thanks!

import random

dice1 = random.randint(1, 2)
user_input = input("Guess a number: ")

if dice1 == user_input:
    print("Well Done!")
else:
    print("Try again")
user1767754
  • 23,311
  • 18
  • 141
  • 164
000
  • 23
  • 1
  • 5

3 Answers3

0

What you are really looking for is a while loop that keeps asking for the hidden number as long as you have the wrong answer. As the user Li357 stated, in Python3 the input is always a string, so you have to convert it to an int. In Python2 you wouldn't have to put the int (just in this specific case)

import random

dice1 = random.randint(1, 2)
user_input = None


while(dice1 != user_input):                          #Keep asking
    user_input = int(input("Guess a number: "))      #Input to int
    if int(user_input) == dice1:                     #Now you check int vs int
        print("Well Done!")
        break                                        #If found, break from loop
    else:
        print("Try Again!")
user1767754
  • 23,311
  • 18
  • 141
  • 164
0

The input() returns a string, so you have a string in user_input. In dice1, you have an integer. Try print(type(user_input)) and print(type(dice1)). You cannot compare values of different types.

Convert the value in user_input to an int, then compare it with dice1, like so:

import random

dice1 = random.randint(1, 2)
user_input = input("Guess a number: ")
user_input = int(user_input)
# You could replace the above two user_input statements with:
# user_input = int(input("Guess a number: ")) # Uncomment before using

if dice1 == user_input:
    print("Well Done!")
else:
    print("Try again")

Running the above code:

Guess a number: 1
Well Done!
>>> 

More about input():

input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

Community
  • 1
  • 1
srikavineehari
  • 2,502
  • 1
  • 11
  • 21
-1

convert the input to an integer:

import random

dice1 = random.randint(1, 2)
user_input = int(input("Guess a number: "))

if dice1 == user_input:
    print("Well Done!")
else:
    print("Try again")
Xero Smith
  • 1,968
  • 1
  • 14
  • 19