Unsupported operand type(s) for 'X': 'NoneType' and 'NoneType'

111 Views Asked by At

I'm currently working on a code and I'm getting this error. Please explain what am I doing wrong in a simple way...help!

s=int(input('input random seed:'))
a=print('The first number is',format(random(50,56)))
b=print('The second number is',format(random(50,56)))
if (a*b)==c:
    print('Your answer is correct.')
4

There are 4 best solutions below

2
Devam Sanghvi On

Problem is you are assigning with print statement that will return None in python

a=print('The first number is',format(random.randint(1,9)))

try this:

import random
s=int(input('input random seed:'))
random.seed(s)
a=format(random.randint(1,9))
b=format(random.randint(1,9))
print('The first number is',a)
print('The second number is',b)
c=input('What is the product of two numbers?')
if (int(a)*int(b))==int(c):
    print('Your answer is correct.')
else:
    print('Your answer is wrong.')
0
user459872 On

The problem is with these lines.

a = print('The first number is',format(random.randint(1,9)))
b = print('The second number is',format(random.randint(1,9)))

print function is used to print the values to the stdout and it does not return any value. A function in python that has no return value will implicitly return None, which means during the runtime the values of a and b are

a = None
b = None

So your if will evaluate to

if (None * None) == <YOUR_C_VALUE>:

Hence the error,

TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
0
Remzinho On

Like the first comment says, on lines 4,5 and 6 of your code you're trying to assign the value of print to your variable, but the built-in print does not return a value. What you want is:

a = random.randint(1,9)

then:

print('The first number is',format(a))

so that your code will do what your trying to achieve. Note that after you get the input from command line for c, you'll have to convert it to int or whatever you want to use, because when you read raw input, it's read as string.

if (a*b)==int(c):
0
The Myth On

In python print statement returns none so you cannot assign values there. You also don't require to conver the numbers into strings.

Try this:

import random
s=int(input('input random seed:'))
random.seed(s)
a= random.randint(1,9)
b= random.randint(1,9)
print(f'The first number is {a}') # f-string
print(f'The second number is {b}') # f-string

c=input('What is the product of two numbers? ')
print('Your answer is correct.') if (a*b)==int(c) else print('Your answer is wrong.')