Search code examples
pythonraw-input

Error in input: Python


I have an input with newline between each string. The end will be noted by a number between 1 to 5:

Input: Ha

Ha

Hee

Hee

Ho

5

I need to accept this as list of strings in python where my list would contain: ['Ha', 'Ha', 'Hee', 'Hee', 'Ho']

After a lot of googling, I tried the following code:

lines = []

sentinel = range(6)

for i in iter(raw_input, [str(s) for s in sentinel]):
    if i=='':
        continue
    else:
        lines.append(i)

print lines

I don't know why but it goes into an infinite loop.

Please help me out!


Solution

  • The issue is with the way iter() interpets the sentinel. It's a single value that indicates the end of iteration. For your sentinel to be hit, raw_input() would actually have to return an identical list, which can never happen (since of course it returns a str).

    If you wrap things up a bit, you can make it work:

    sentinel = range(6)
    
    def anything_but(values):
        values = map(str, values)
        def inner():
            i = raw_input()
            if i in values:
                return None
            return i
        return inner
    
    lines = []
    for i in iter(anything_but(sentinel), None):
        lines.append(i)
    
    print lines
    

    In this case, None is the sentinel value which will be returned if a number 0-5 is entered. As an aside, if you wanted 1-5 as you mentioned you should use range(1, 6) instead.

    However, you're probably better served doing it with a generator:

    sentinel = range(6)
    
    def anything_but(values):
        values = map(str, values)
        i = raw_input()
        while i not in values:
            yield i
            i = raw_input()
    
    lines = []
    for i in anything_but(sentinel):
        lines.append(i)
    
    print lines