I don't understand why this isn't working.

0 Anthony Armfield · May 22, 2015
Here is the code:

import random
userNumber = input("Please enter a number between 1 and 10... ")
x = random.randrange(1, 11)

if x == userNumber:
print("You got it!!! Your number was", x)
else:
print("You didn't get the right number!!")
print("The random number was", x)


I just want to be able to put in a number and compare that number to a randomly generated number.  I changed the range to (1, 3) so that refreshing and testing was easier.  What I don't understand is why I get the following:

Please enter a number between 1 and 10... 2
You didn't get the right number!!
The random number was 2

I put in 2 and the random number was 2, but the program thinks x != userNumber

Thanks!

Post a Reply

Replies

Oldest  Newest  Rating
0 Colonel Panic · May 22, 2015
Well, you are only giving yourself one chance, and even when you use randome.randrange(1,3), it can still be either 1 or 2, so maybe it was 1 and not two.  First number is inclusive, second is not in the randrange method.    For example:


>>> import random
>>>
>>> for i in range(1,10):
...     print random.randrange(1,3)
...
2
1
2
1
1
1
1
2
2
+2 Pavel Dimi · May 22, 2015
You need to cast your input tp int
0 Anthony Armfield · May 23, 2015
I figured it out, guys!

Instead of having this:

userNumber = input("Please enter a number between 1 and 10... ")

I needed to have this:

userNumber = int(input("Please enter a number between 1 and 10... "))

Sorry for missing the code tag, will do that in the future.
  • 1

Python

107,358 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator