c++ – Whats the equivalent for while (cin >> var) in python?

c++ – Whats the equivalent for while (cin >> var) in python?

Theres 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 youll need to convert it in a separate step:

        var = int(var)

This could be helpfull.

import sys

for line in sys.stdin:
    #Do stuff

c++ – Whats the equivalent for while (cin >> var) in python?

In C++ cin >> n has a dual nature: It acts both as a boolean expression indicating whether it has read (true) or has not read (false) an element in the sequence, and as a channel in operator that gets an element (if there are any left). Sadly, in python the closest you can get right out-of-the-box is to doing n = input(), which also acts as a channel in BUT does not act as a boolean expression.

In order to solve that (by making things C++onic instead of Pythonic) you could define an auxiliary function called, conveniently, cin(). This function will have one parameter n, which will actually work as if it was a C++ pass-by-reference (i.e. an input/output parameter). To simulate that behaviour, here I make n to be a list object with one element -in this case an integer number-, taking advantage of Python lists aliasing properties. This way, when n[0] changes in the auxiliary method, the value change will also be reflected in the main method n[0] value each time cin(n) call returns true… without any further do.

def cin(n):
    #function that woks equally to doing cin >> n
        n[0] = int(input())
        return True
        return False

def main():
    #C++ like main method (for illustrative/comparative purposes)
    n = [0]
    while cin(n):
        #MESSAGE: do someting with n[0] (watch out, n is list object with one element)


For example, in the previous code, if you wanted to print the double of the elements of a sequence of numbers with an indefinite number of them, you would simply change the line #MESSAGE for the following:


Or, another example, if you wanted to implement a recursive solution to print in inverse order the elements of a sequence (also with indefinite length) and having the constraint of NOT using a list with more than one element you would, again, need to change the line #MESSAGE for the following:


Leave a Reply

Your email address will not be published. Required fields are marked *