1
I am trying to receive command from sys.stdin until it reaches a limit n
lines, and then finish the execution automatically.
My code is as follows:
import sys
A = []
n = int(input("number of nodes: "))
for line in sys.stdin:
if len(line.split()) == 2:
A.append(line.split())
else:
print("Requires two integers, ie: 1 2. You typed:", line)
print(A)
This code will ask for an initial value, which will be assigned to n
. After that you’ll be adding number pairs to lista A
. I wanted you to stop requesting command after the lista
have a size equal to n
Example of input would be:
> 2
> 1 2
> 2 3
and the output would be:
[['1','2'], ['2','3']]
But the way it is now it keeps adding to the list in an undetermined way, until the user of the sign they have finished typing. How do I make it automatic to end the execution once the len(A) == n
?
if I put at the end of the code, after the
else
but before theprint(A)
, oneif len(A) == n: break
, works as I would like, but I believe there is a more appropriate way to achieve this– Pirategull