Sergio
Sergio

Reputation: 1

Creating a small program in python

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')

Upvotes: 0

Views: 89

Answers (3)

Robin Koch
Robin Koch

Reputation: 726

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.

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49320

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.

Upvotes: 2

Prajwal
Prajwal

Reputation: 4000

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:

Upvotes: 1

Related Questions