-1

here is sample test case for input

c++ code

while( cin >> variable)
 {
   //your code
 }

I want to convert this code into python, input is stream of integers like:

J...S
  • 5,079
  • 1
  • 20
  • 35
TheSohan
  • 442
  • 3
  • 18

2 Answers2

2

To achieve the same in python you can catch an EOFError, e.g.:

while True:
    try:
        variable = int(input())
    except EOFError:
        break
    # your code

You can manually terminate the list of inputs with Ctrl-D or it will automatically terminate if you pipe in the input, e.g. cat nums | myscript.py

In Py 3.8 with assignment expressions you can change this to

try:
    while variable := int(input()):
        <do-something-with-variable)
except EOFError:
    pass

Or suppressing the exception with a context manager:

from contextlib import suppress

with suppress(EOFError):
    while variable := int(input()):
        <do-something-with-variable)
AChampion
  • 29,683
  • 4
  • 59
  • 75
0

Use

s=input("Enter: ")
s=[int(x) for x in s.split()]

input() will return a string version of the input. split() is applied on this string with space as delimiter.

Each element of the list returned by split() is converted to an integer with int().

Edit:

To accept input till EOF, you could do

import sys
s=sys.stdin.read()
if(s[-1]=='\n'):
    s=s[:-1]
s=[int(x) for x in s.split()]
J...S
  • 5,079
  • 1
  • 20
  • 35