Create a program that will keep track of items for a shopping list. The program should keep asking for new items until nothing is entered (no input followed by enter key). The program should then display the full shopping list
How do I write the condition so it works?
The code I'm writing looks like this:
x = []
i = 0
while i != '':
x.append(input('what u want?'))
i = i 1
print(x)
```
`
CodePudding user response:
Hitting Enter only on input()
returns an empty string. Values such as empty containers, zero-length strings, or numerically equivalent to zero are considered false in conditional statements.
Python >= 3.8 (supports := operator):
items = []
while item := input('Item? '):
items.append(item)
print(items)
Python < 3.8:
items = []
while True:
item = input('Item? ')
if not item: break
items.append(item)
print(items)
Demo:
Item? one
Item? two
Item? three
Item?
['one', 'two', 'three']
CodePudding user response:
Find len
of user input & check with if accordingly
x = []
while 1:
ask= input('what u want?')
if len(ask)>0:
x.append(ask)
else:
print("Good bye")
break
print(x)
output #
what u want?rice
what u want?sugar
what u want?
Good bye
['rice', 'sugar']