Pete Buchanan Pete Buchanan - 11 months ago 34
Python Question

Python IF ELSE statement now working

Simple question for some. 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:

from random import randrange

#Display Welcome
print("Number guessing game")

#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")


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.