3

So, I recently started learning python and I am in the raw_input() section.

So while I was trying out different things, I made an error (at least that's what I think for now). Can someone please explain what is the difference between the two statements?

  1. var1 = int(raw_input())

  2. var1 = int((raw_input())

I know that the first one waits for an input from the user and assigns it to the variable var1 but, in the second case, this is the output I am getting.

>>> x = int((raw_input()) On pressing enter, it just shows the ellipses and waits for a user input.

... 12 Twelve was my input and then I get the following error.

File "<stdin>", line 2 12 ^ SyntaxError: invalid syntax

I know it clearly says it is a Syntax Error but shouldn't it even accept the statement? Why does it wait for an in input?

Thank you.

Python Version: 2.7 OS: Windows

2 Answers2

10

var1 = int((raw_input()) has three left parentheses and two right ones. Until you complete the expression with another right parentheses, Python thinks you have not finished writing the expression. That is why it shows an ellipsis.

When you type "12", the full expression becomes var1 = int((raw_input())12, which is not valid syntax because you can't have a number immediately after a closing paren.

Kevin
  • 74,910
  • 12
  • 133
  • 166
2

Expanding on Kevin's answer, here's why you would want Python to behave like this. In this case it provides you with a rather confusing error, but if you did something like

>>> x = int((raw_input())
... + "123")

then it could be parsed as

>>> x = int((raw_input()) + "123")

or

>>> x = int(raw_input() + "123")

which would be a valid expression. This becomes useful when you want to write very long expressions which don't fit on one line. Any time you have an extra open parenthesis you can continue the expression on a new line. One case you might want to do this is:

if (check_a_condition(a) and check_a_condition(b) or
    check_a_condition(c) and check_a_condition(d)):
    pass
porglezomp
  • 1,333
  • 12
  • 24
  • Thank you so much for shedding more light on the topic. Now it becomes more clear to me. Just one question, I am away from my laptop now, but if I did execute the following command `x = int((raw_input()) + "hello")` and my input was any integer or string, it would result in an error right? Please correct me if I am wrong. – DigvijaySingh Sep 03 '15 at 18:14
  • Yeah, that's not a great example, `"42hello" ` will never be a valid integer. I'll change it. – porglezomp Sep 03 '15 at 18:17
  • Great. Thanks again. – DigvijaySingh Sep 03 '15 at 18:22