0

I have created the following Python script named week1_1.py:

import sys
input = sys.stdin.read()
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)

However, when I call it from within my Jupyter Notebook I get the following exception:

%run -i week1_1 2 3

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
D:\Mint_ns\week1_1.py in <module>()
      8 input = sys.stdin.read()
      9 tokens = input.split()
---> 10 a = int(tokens[0])
     11 b = int(tokens[1])
     12 print(a + b)

IndexError: list index out of range

What might be the cause of this exception?

1
  • What does print(tokens) or print(len(tokens)) show? tokens is probably an empty list. Commented Aug 15, 2018 at 1:33

4 Answers 4

1

To get user input in Jupyter Notebook, use input() (or raw_input() for Python 2):

Example 2 showing input

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

1
input_str = input()
tokens = input_str.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)

ouput:
1 2
3

you can use input() to replace sys.stdin.read().

Why you cannot use sys.stdin.read()? the sys.stdin.read() will read stdin until it hits EOF. So I guess when you run it in jupyter notebook, it will read EOF when you run the cell.(I am not sure.)

But input() will run normallly in jupyter notebook. I recommend you to use input() rather than sys.stdin.read() when get keyboard input.

Comments

0

A simpler way is to use raw_input instead of stdin.read:

tokens = raw_input().split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)

Comments

0

OR:

print(sum(int(i) for i in input().split()))

Example output:

1 1
2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.