2

Started programming today. Really interested in getting a head start in my degree next year.

I'm using newboston to teach myself and it's going OK so far. struggling with a real simple snippet of code though.

I want a message to come up saying "What is 1+1." The user inputs an anwser and IF it's 2, print a correct message. If not, print incorrect.

input ("What is 1 + 1\n")
if input is 2:
    print ("correct")
else:
    print("incorrect")

C:\Python31\python.exe "C:/Users/JoeNa/Desktop/Python Study/Experimenting.py"
What is 1 + 1

incorrect

Process finished with exit code 0
Maroun
  • 94,125
  • 30
  • 188
  • 241
RhaegoT
  • 63
  • 4

6 Answers6

3

Write it as follows:

result = input ("What is 1 + 1\n")
if int(result) == 2:
    print("correct")
else:
    print("incorrect")

If you want to handle the result from input(), you have to store it in a new variable. After that, if you expect it to always be an integer, cast it using the int keyword.

Also, try not to use a variable name that is the same as the input() keyword.

Also, as an additional note, use == instead of is in this case scenario. I would suggest reading up on the usage of the is keyword vs the equals operator.

William Troup
  • 12,739
  • 21
  • 70
  • 98
2
my_val = int(input("What is 1 + 1\n"))

if my_val == 2:
    print ("correct")
else:
    print("incorrect")

input returns a string so you have to cast it to an int.

Also, don't name your variables after built-in keywords or functions in Python as you could override them and lose access to them when you want to use them later on in your code. Consider this:

>>> input = 'hello'
>>> s = input('enter your name')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> 

You can't call the input function again in your program because you have set input to a string, that's why the Python interpreter brings up that error.

The ZetCode Python website has a list of keywords in Python.

is is used to compare objects by their identity, while == compares two objects by their values. You have to understand these as it could lead to complex errors when you interchange them.

Consider this:

>>> a = [1,2]
>>> b = [1,2]
>>> a is b
False
>>> a == b
True

>>> id(a)
140109265441288
>>> id(b)
140109265454472
>>> 

a and b are two different objects so they are not the same by their identity but are equal by their values.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
danidee
  • 9,298
  • 2
  • 35
  • 55
  • Alternatively, `my_val = input("What is 1 + 1\n")` `if my_val == "2"` etc, which saves performing a conversion. – PM 2Ring Mar 02 '16 at 16:01
  • yeah...i just guessed that he wanted to compare two integers, that's a common pitfall for many beginners in python – danidee Mar 02 '16 at 16:02
  • Sure! I just find it fascinating that all the answers advocate converting the input string to int, rather than doing a string comparison. Of course, in a more complicated program you almost always want to convert number strings to actual numbers. BTW, consider breaking up your text into separate sentences rather than one big sentence. – PM 2Ring Mar 02 '16 at 16:05
1

Several things:

  1. input() is a function which reads user input from the keyboard as string
  2. you call input() but never save the value it returns to a variable
  3. you compare with "is" instead of "==" (although these may be equivalent in some cases check out the differences and learn when to use which)
  4. when comparing make sure you don't compare apples with oranges (string with int)
gplayer
  • 1,741
  • 1
  • 14
  • 15
1

When you use input ("What is 1 + 1\n"), the user's input is stored as a String (Text). Therefore, you need to convert the String into a integer in order to compare it to another integer.

try the following:

userInput = input ("What is 1 + 1\n")
if int(userInput) == 2 
    print("correct")
else:
    print("incorrect")

int(userInput) will convert string into an integer

Rana
  • 1,675
  • 3
  • 25
  • 51
1

Here are a few tips, some of which are a matter of opinion:

input ("What is 1 + 1\n")

Becomes:

user_input = input("What is 1 + 1? ")

Where did user_input come from? I just made it up. It is just a name which now refers to the answer entered by the user. The input() function returns a string, which you must give a name (otherwise its a bit of a waste of time). Don't use the name input though, that will replace the built-in input() function! Personally I don't put a newline (\n) at the end of the question, but I always put a space.

So, user_input is of class str (a text string) whereas 2 is of class int (an integer). You are trying to compare objects of different classes - usually that is not allowed. However, you are not comparing the values, is compares references. Usually (9 times out of 10) you want to find if values are equal, so use == instead.

if input is 2:
    print ("correct")
else:
    print("incorrect")

Becomes:

if int(user_input) == 2:
    print("correct")
else:
    print("incorrect")

Notice as well that I have paid attention to being consistent with things like spacing before parentheses. This is just style, but is worth noting. At some point look at PEP008, which is the style guide for Python.

cdarke
  • 42,728
  • 8
  • 80
  • 84
0

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))
Community
  • 1
  • 1
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290