Reputation:
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
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
Reputation: 51857
Here are a few tips:
'this "kind" of string'
to avoid \
raw_input
, not str(input(...))
. If you're using Python3, you don't need to cast to str, it's already a str..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
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