19mddil
19mddil

Reputation: 43

How can I give many inputs in just one line in the console like in C++?

In C++ code, I can give 1 2 3 4 5 6 7 8 then press enter in console to have output like,

1 2
3 4
5 6
7 8

But in Python code when I tried to generate the same output by the inputting in the console like 1 2 3 4 5 6 7 8 and enter but it generated an error... Rather I can give input and have output in console like this in Python:

1 2
1 2
3 4
3 4
5 6
5 6
7 8
7 8

I can see my code is not enough in Python...

I tried putting input().split() in a loop.

/* C++ */
int x,y;
for (int i=0; i<4; i++){
    cin>>x>>y;
    cout<<x<<y<<endl;
}
# Python
for i in range(4):
    x, y = input().split()
    print(x, y)

I expected Python could take those inputs just in only one line and generate the output in the console like in C++.

Upvotes: 0

Views: 101

Answers (2)

Saif Faidi
Saif Faidi

Reputation: 529

take a look to zipping and iterators before using this code :

iterator = iter(input().split())
for x,y in zip(iterator,iterator):
    print(x,y)

input :

1 2 3 4 5 6 7 8

output :

1 2
3 4
5 6
7 8

Upvotes: 2

Tomerikoo
Tomerikoo

Reputation: 19403

This is because in contrary with c++, in Python every time you call input it waits for new input from the user. So, if you expect to get a 8 numbers input and print it in couples you should take the input one time before the loop. Like so:

nums = input().split()
for i in range(0, len(nums), 2):
    print(nums[i], nums[i+1])

And this on an input of 1 2 3 4 5 6 7 8 gives:

1 2
3 4
5 6
7 8

Upvotes: 1

Related Questions