bobthepanda
bobthepanda

Reputation: 31

while with raw_input creating an infinite loop

In these lines:

foo = []

a = foo.append(raw_input('Type anything.\n'))
b = raw_input('Another questions? Y/N\n')

while b != 'N':
    b = foo.append(raw_input('Type and to continue, N for stop\n'))
    if b == 'N': break

print foo

How to do the loop break? Thanks!

Upvotes: 0

Views: 720

Answers (4)

Troy
Troy

Reputation: 36

You are assigning b to the result of a list append which is None. Even if you were lookking at foo, you would be looking at the list created by the foo.append and then comparing it to the charcter 'N'. Even if you only type N at the input, the value of foo would at least look like ['N']. You could eliminate b altogether with:

while True:
    foo.append(raw_input('Type and to continue, N for stop\n'))
    if 'N' in foo: break

Though this would leave the 'N' character in your list. Not sure if that is intended or not.

Upvotes: 0

elyase
elyase

Reputation: 40963

Just check for the last element added to foo:

while b != 'N':
    foo.append(raw_input('Type and to continue, N for stop\n'))
    if foo[-1] == 'N': break   # <---- Note foo[-1] here

Upvotes: 0

Blam
Blam

Reputation: 2965

This is the way to do it

foo = []

a = raw_input('Type anything.\n')
foo.append(a)
b = raw_input('Another questions? Y/N\n')

while b != 'N':
    b = raw_input('Type and to continue, N for stop\n')
    if b == 'N': break
    foo.append(raw_input)

print foo

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304137

list.append returns None.

a = raw_input('Type anything.\n')
foo = [a]
b = raw_input('Another questions? Y/N\n')

while b != 'N':
    b = raw_input('Type and to continue, N for stop\n')
    if b == 'N': break
    foo.append(b)

Upvotes: 1

Related Questions