1

I have my first program I am trying to make using python. The IF ELSE statement is not working. The output remains "Incorrect" even if the correct number is inputted by the user. I'm curious if it's that the random number and the user input are different data types. In saying that I have tried converting both to int with no avail.

Code below:

    #START
from random import randrange

#Display Welcome
print("--------------------")
print("Number guessing game")
print("--------------------")

#Initilize variables
randNum = 0
userNum = 0

#Computer select a random number
randNum = randrange(10)

#Ask user to enter a number
print("The computer has chosen a number between 0 and 9, you have to guess the number!")
print("Please type in a number between 0 and 9, then press enter")
userNum = input('Number: ')

#Check if the user entered the correct number
if userNum == randNum:
    print("You have selected the correct number")
else:
    print("Incorrect")
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

2

If you are using Python 3, change the following line:

userNum = input('Number: ')

to

userNum = int(input('Number: '))

For an explanation, refer to PEP 3111 which describes what changed in Python 3 and why.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
2

On Python 3 input returns a string, you have to convert to an int:

userNum = int(input('Number: '))

Note that this will raise a ValueError if the input is not a number.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154