c++ code
while( cin >> variable)
{
//your code
}
I want to convert this code into python, input is stream of integers like:
c++ code
while( cin >> variable)
{
//your code
}
I want to convert this code into python, input is stream of integers like:
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)
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()]