You have multiple points of confusion here. Let's look at the docs for input:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So, input()
returns a string. You're calling the function in your code, but you're not actually storing the return value anywhere. Good variables are descriptive names. In your code you're looking for an answer
, so that's a good choice. That makes the start of your code look like this:
answer = input('What is 1+1?\n')
Now if you remember from the documentation, input()
returns a string.
'2'
"2"
'''2'''
These are all representations of strings.
2
As others have mentioned, you can check the type of a variable or value by using the type()
function:
>>> type(2)
<class 'int'>
>>> type('2')
<class 'str'>
That is a number. If you try to compare a number to a string, they're not equal:
>>> 2 == '2'
False
So if we want to get a proper comparison, we'll need to either compare strings or convert the answer
to a number. While technically either option works, since 1+1
is math and math is about numbers, it's probably better to convert it to a number:
>>> int('2') == 2
True
Aside
Currently you're using is
. If you check the python documentation on comparisons, you'll see that is
compares object identity. But what does that mean? You can find the identity of an object in Python by using the id()
function. You were checking if input is 2:
-- which *does** make sense in English, but not in python --and what does that actually check? Well, first off:
>>> input
<built-in function input>
input
is a function. So what you're checking is if the input function is the number 2
(not the value two, but the actual object). The id is pretty accidental and will probably change between runs of Python. Here's what mine reports:
>>> id(input)
140714075530368
>>> id(2)
140714073129184
An interesting note - CPython does some interesting things with small numbers, so it's possible that 2 is 2
returns True, but that's not necessarily guaranteed. But this is:
val = 2
other_val = val
val is other_val # Will be true
Putting it all together
Well, now that we know what to do, here is what your program looks like:
answer = input('What is 1+1?\n')
if int(answer) == 2:
print('Correct!')
else:
print('Incorrect')
What if someone provides an input that isn't a number, though? Depending on how robust you want your program, you can approach it one of two ways. The first, ensuring that the string is just digits:
if answer.isdigit() and int(answer) == 2:
print('Correct!')
Or, you can catch the exception that's raised:
try:
if int(answer) == 2:
print('Correct!')
else:
print('Incorrect!')
except ValueError:
print('***ERROR*** {!r} is not a number!'.format(answer))