user7733823
user7733823

Reputation:

How do I break out of a loop without first appending to my list?

How do I prevent the following code from appending the break command "N" to the list, and therefore printing "N"?

xlist=[]
item=str(input("Item to add? (\"N\" to quit)"))
xlist.append(item)
while item != "N":
    item=str(input("Item to add? (\"N\" to quit)"))
    xlist.append(item)
    if item == "N":
        break

print(xlist)

Upvotes: 0

Views: 203

Answers (3)

gchelfi
gchelfi

Reputation: 89

You can also simplify your program this way:

xlist=[]
item=input("Item to add? (\"N\" to quit)")
while item != "N":
    xlist.append(item)
    item=input("Item to add? (\"N\" to quit)")

Edit: Removed superfluous str() calls as suggested in a comment.

Upvotes: 1

Wayne Werner
Wayne Werner

Reputation: 51857

Here are a few tips:

  • you can use 'this "kind" of string' to avoid \
  • you can actually avoid having the same line of code by re-introducing an if statement
    • If you're using Python2 (as a beginner you shouldn't be) you should be using raw_input, not str(input(...)). If you're using Python3, you don't need to cast to str, it's already a str.
    • You can use the .lower() (or .upper()) method to let the user use n or N.

This is what that looks like:

xlist = []
item = ''
while True:
    item = input('Item to add? ("N" to quit): ')
    if item.lower() == 'n':
        break
    else:
        xlist.append(item)

Upvotes: 0

SiHa
SiHa

Reputation: 8421

In your while loop, item != "N": will never become false, because you manually break out of the loop.

A better way of having a while lop that will end upon a certain input, which avoids having two input statements would be to use an infinite while loop (while True), and then break out when the desired condition is met:

xlist=[]
while True:
    item=str(input("Item to add? (\"N\" to quit)"))
    if item.upper() == "N":
        break
    xlist.append(item)

print(xlist)

Also, I added the upper() so that it will accept either n or N

Upvotes: 0

Related Questions