0

I'm trying to make a program in Python 3.5 that asks the user to enter a number from 1 to 9. The the program will also guess a number from 1 to 9. If the user guesses the same number correctly, then the program will print Correct . Otherwise, the program will print Wrong. I wrote a program. Everything went fine with my code. However, when I guessed a number correctly, the program suddenly wrote Wrong instead of Correct. What am I doing wrong?

Here is my code:

print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
import random
random = print(random.randint(1,9))
if int(x) != random:
    print ('Wrong')
else:
    print ('Correct')
2
  • 2
    You are assigning None to random Commented Dec 1, 2016 at 9:55
  • 1
    It is not advisable to use a variable named random. Commented Dec 1, 2016 at 9:57

3 Answers 3

2

You are saving the result of a print() call (and masking random). print() returns None, so it will always be unequal to an integer, and therefore always "wrong."

import random

print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
r = random.randint(1,9)
if x != r:
    print('Wrong')
else:
    print('Correct')

Also note that I've moved the import statement to the top, avoided a second int() cast on something you've already done that to, and removed the space between the print reference and its arguments.

Sign up to request clarification or add additional context in comments.

Comments

1

Here is the mistake,

random = print(random.randint(1,9))

You need to do something like this.

random = random.randint(1,9)
print(random)

Also, you have already converted the input to int so, you can do just this.

if x != random:

Comments

0

As pointed out your mistake is the line

random = print(random.randint(1,9))

But why?

functions (like print() take something, do something (with it) and give something back.

Example: sum(3,4) takes 3 and 4, may add them and returns 7.

print("Hello World") on the other hand takes "Hello world", prints it on the screen but has nothing useful to give back, and therefore returns None (Pythons way to say "nothing").

You then assign None to the name random and test if it equals your number, which it (of course) doesn't.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.