Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent for while (cin >> var) in python?

Tags:

c++

python

input

In online contests, when the length of input is not specified and reading the input file directly through the program is not possible, one can use this code in C++:

while (cin >> var)
{
    //do something with var
}

What's the equivalent for python?

  • Without using any file-related function such as open() write() ...
like image 217
Milad R Avatar asked Mar 11 '15 14:03

Milad R


People also ask

What is the equivalent of cout in Python?

So, cout stands for “character output”. Much like the Python print statement, cout is used to print to the standard output device, which is typically your screen.

What does cin >> n mean in C++?

cin is the standard input stream. Usually the stuff someone types in with a keyboard. We can extract values of this stream, using the >> operator. So cin >> n; reads an integer. However, the result of (cin >> variable) is a reference to cin .

How do you get output in Python?

The basic way to do output is the print statement. To end the printed line with a newline, add a print statement without any objects. This will print to any object that implements write(), which includes file objects.


2 Answers

There's no direct equivalent in Python. But you can simulate it with two nested loops:

for line in sys.stdin:
    for var in line.split():

If you need something other than a string you'll need to convert it in a separate step:

        var = int(var)
like image 142
Mark Ransom Avatar answered Sep 22 '22 11:09

Mark Ransom


This could be helpfull.

import sys

for line in sys.stdin:
    #Do stuff
like image 20
Enpi Avatar answered Sep 18 '22 11:09

Enpi