I Have a list, and every time I enter "N" in my program I want the list to print the contents of the next index.
categories = ["Produce", "Meat", "Dairy" ,"Misc"]
...
elif item == "N":
for d in categories[:1]:
d = categories[0]
d += 1
print(d)
I understand that the above code is trying to add an integer to a string and throwing the error. What I haven't been able to figure out is how to increment the index.
I have looked at a few other posts concerning similar problems but it the solutions aren't clicking for me out of context.
Sample output of what it should look like
Add Item to list
Produce
>>Tomatoes
>>Grapes
Meat
>>Hamburger
Dairy
>>
Entire program
def add_item():
exit_list = ["F", "Finished"]
lists = []
start = input("Would you like to add an item to the list? Y/N")
print("Add Item to list")
categories = ["Produce", "Meat", "dairy","snacks/boxed goods", "Cans", "Misc"]
print(categories[0])
while start in ('y', 'Y'):
item = input(">>")
if item in exit_list:
break
elif item == "N":
for d in categories[:1]:
i = 0
i +=1
d = categories[i]
print(d)
elif item:
lists.append(item)
else:
print("ok")
print(lists)
return lists
add_item()
This code will keep track of an index and increment it each time it's used:
i = 0
categories = ["hey", "1", "2" ,"3"]
...
elif item == "N":
print(categories[i])
i += 1
And note that this code will eventually go out of bounds. If you want to wrap around you can do e.g. % len(categories) on i.
Most of the time it is possible, if not better, to avoid using index in Python. One way in your case would be to use a generator on your list. The following code will quit when the user enters q, print the next item when the user enters n, and do nothing if the input is something else.
categories = ["hey", "1", "2" ,"3"]
user_input = None
# Transform your list into an iterator
categories = iter(categories)
# While the user doesn't want to quit
while user_input != "q":
# The user's input is transformed to lower case
user_input = input("What do you want to do ? ").lower()
if user_input == "n":
try:
# We print the next value on the iterator i.e. the next
# value in your list
print(next(categories))
except StopIteration:
# Raised when the iterator reached the end i.e. when we
# have printed all the values in the list
print("You've printed all the list!")
break
One possible output is:
What do you want to do ? hello # Nothing happens here
What do you want to do ? n
hey
What do you want to do ? n
1
What do you want to do ? n
2
What do you want to do ? n
3
What do you want to do ? n
You've printed all the list!
Note that this example is using Python3+
def add_item():
exit_list = ["F", "Finished"]
lists = []
start = input("Would you like to add an item to the list? Y/N")
print("Add Item to list")
categories = ["Produce", "Meat", "dairy","snacks/boxed goods", "Cans", "Misc"]
print(categories[0])
i=0
while start in ('y', 'Y'):
item = input(">>")
if item in exit_list:
break
elif item == "N":
i +=1
print(categories[i])
elif item:
lists.append(item)
else:
print("ok")
print(lists)
return lists
add_item()
Related
The code is a follows:
n=str(input("Enter the name of the item:"))
p=int(input("Enter the price of the item:"))
r=int(input("Enter the quantity of the item:"))
tot=p*r
GST=tot+(5/100)*tot
print("Bill:")
print("Item", "\t\t\tPrice", "\tQuantity", "\tGST", "\tTotal cost")
print(n,"\t\t", p, "\t", r, "\t\t5%","\t", GST)
The number of items n must be given as user input
Try converting 'v 'variable' to list so u can access it using indexes and even user can enter many items to it
why don't you make a loop like:
stopped = False
items = []
prices = []
quantities = []
while not stopped:
items.append(str(input("Enter the name of the item:")))
prices.append(int(input("Enter the price of the item:")))
quantities.append(int(input("Enter the quantity of the item:")))
c = ""
while c not in ["yes", "no"]:
c = input("continue ? type yes or no")
if c == "no":
stopped = True
# then make your processing of these lists.
so i have a code which loops until the user types cancel and allows the user to input things into a list and then see the list if they want to. but i have a problem wherein if i want to see the list the user has to input again and the data i typed when i added to the list is gone. here is the code pls help me im pretty new to python.
answer=""
def addlist():
list=input("what would you like to add? ")
print("added successfully")
return list
def showlist():
list=addlist()
print(list)
while answer !="cancel":
answer=input("what would you like to do?, 1 for add to list, 2 for show list, cancel to close")
if answer=="1":
addlist()
elif answer=="2":
showlist()
else:
print("wrong value")
So we've got a few problems here:
addlist doesn't actually create a list, it creates a string.
showlist depends on addlist, when really we should be looking for a common list that we toss everything into (assuming you actually want to work with a list)
Your indentation in your while loop is incorrect
def addlist():
item = input("what would you like to add?")
return item
def showlist(mylist):
print(mylist)
mylist = []
answer = ""
while answer != "cancel":
answer = input("what would you like to do?, 1 for add to list, 2 for show list, cancel to close")
if answer == "1":
add_item = addlist()
mylist.append(add_item)
print("added successfully")
elif answer == "2":
showlist(mylist)
else:
print("wrong value")
That above seems to do the trick.
You seem to have a grasp on return statements, so how about you pass each of those functions a common list as I did mylist and have them do stuff with that.
I changed addlist to actually just get the item we want to add to the list and then return that item and append it outside of the function. In showlist I pass mylist to it via: showlist(mylist) and then print the list I get in that function.
You should create a list element in order to append your items in it. You can see more here. One way to do what you want is like this:
answer = ""
temp_list = []
def addlist():
item = input("what would you like to add? ")
temp_list.append(item)
print("added successfully")
def showlist():
print(temp_list)
while answer != "cancel":
answer = input(
"what would you like to do?, 1 for add to list, 2 for show list, cancel to close")
if answer == "1":
addlist()
elif answer == "2":
showlist()
else:
print("wrong value")
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a function that allows a user the ability to add data via input. I would like to add a confirmation step that will allow them to answer yes or no to continue. If they select no it should allow them to restart the function of adding data to the list. I also want to make sure they answer with Y, YES, y, yes, N, NO, n, no. What would be the best way to accomplish this? I've tried several solution I've found online but I end up not being able to get out of the loop of asking yes or no. Thanks in advance.
def item_list(): # Create a list
items = []
item_int = 0
while 1:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
if item == "":
break
items.append(item)
return items
items = item_list()
print(items)
answer = input("Continue?")
if answer.lower() in ["y","yes"]:
# Do stuff
else if answer.lower() in ["n","no"]:
# Do other stuff
else:
# Handle "wrong" input
My answer would be extension of #B. Plüster but it allows slightly bigger range of the inputs and prevent rejections of case-sensitive typos:
answer = input("Continue?")
if answer.upper() in ["Y", "YES"]:
# Do action you need
else if answer.upper() in ["N", "NO"]:
# Do action you need
You could create a wrapper function which calls your other function. In the wrapper function, use another loop to confirm items.
# wrapper function
def item_list_wrapper():
while True:
# call your function at the start of each iteration
final_items = item_list()
# confirm with the user
print('\nThese are your items:', ', '.join(final_items))
user_input = input('Confirm? [Y/N] ')
# input validation
if user_input.lower() in ('y', 'yes'):
break
elif user_input.lower() in ('n', 'no'): # using this elif for readability
continue
else:
# ... error handling ...
print(f'Error: Input {user_input} unrecognised.')
break
return final_items
# your original function
def item_list():
items = []
item_int = 0
while 1:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
if item == "":
break
items.append(item)
return items
Then call it as you'd normally call it.
items = item_list_wrapper()
print(items)
In the item_list_wrapper function, note that the line with items = item_list() will renew the list every time. If you want the user to continue adding existing items, you could switch the order of commands around.
def item_list_wrapper():
final_items = item_list() # call the function at the start
while True:
# confirm with the user
print('\nThese are your items:', ', '.join(final_items))
user_input = input('Confirm? [Y/N] ')
# input validation
if user_input.lower() in ('y', 'yes'):
break
elif user_input.lower() not in ('n', 'no'):
# ... error handling ...
print(f'Error: Input {user_input} unrecognised.')
break
# call your function at the start of each iteration
new_items = item_list()
# add new items to previous items
final_items += new_items
return final_items
Don't know whether this is efficient enough.
items = list()
tr = [" Y", "YES", "y", "yes"]
fs = ["N", "NO", "n", "no"]
item_int = 0
def item_list(): # Create a list
global item_int
global items
response = input("\nDo you want to enter data: ")
if response == "":
return
if response in tr:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
items.append(item)
elif response in fs:
item_int=0
print("List cleared!")
items.clear()
item_list()
item_list()
print(items)
I'm learning Python and I'm trying to make shopping List
where you can add items
first it will ask you to add the items if the shopping list is empty
it will be added automatically if not it will ask you where you would like
to put the item (index)
but also I'm trying to make the program exit in certain condition like DONE
or HELP or SHOW but even that i put a condition for that but it's not working can anyone help me with this
hope I explained enough
import os
shopping_list =[]
# Function for clearing the screen
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def show_help():
print("Enter 'Done' if you finish adding item \n Enter 'Show' to show your items \n Enter 'Help' toshow this help ")
# Function to show the items that you've entered to the list
def show_item():
clear_screen()
index = 1
for item in shopping_list:
print("{} {}.".format(index,item))
index += 1
# Function to add items to the list
def add_to_list():
while True:
new_item = input("Please enter the item that you would like to add to your shopping list ")
if shopping_list and ((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW")):
position = input("Where you would like to add {} to the list \n press 'Enter' if you want to add to the end of the list".format(new_item))
position = abs(int(position))
shopping_list.insert(position - 1 , new_item)
show_item()
else:
if new_item.upper() == "DONE":
break
elif new_item.upper() == "SHOW":
show_item()
continue
elif new_item.upper() == "HELP":
show_help()
continue
else:
shopping_list.append(new_item)
show_item()
show_help()
add_to_list()
Welcome to stackoverflow. I think your logic statement is wrong, you need and instead of or. Right now all you need for the statement in the parentheses to be true, is that new_item.upper() is at least not one of those three words. It actually can't equate to False since two of the three are always true.
((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW"))
If you have for example done the first statement is False ,but the other two are True, adding up to True in or-Statements.
>>> new_item = 'done'
>>> print((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW"))
True
So I am looking for a way to add separate items to a list in the form of individual dictionaries that contain the grocery item's name, price, and quantity. I only started programming a few weeks ago so please forgive my horrendous code and beginner mistakes.
grocery_item = dict()
current_item = dict()
grocery_history = []
choice = 0
stop = True
while stop == True:
current_item['name'] = str(input('Item name: '))
current_item['quantity'] = int(input('Amount purchased: '))
current_item['cost'] = float(input('Price per item: '))
grocery_history.append(current_item)
choice = str(input('Press c to continue or q to quit'))
if choice == 'c':
stop = True
else:
stop = False
print(grocery_history)
When I input the information of two items (ie spam and eggs) I get the following output:
[{'name': 'Eggs', 'quantity': 12, 'cost': 1.5}, {'name': 'Eggs', 'quantity':
12, 'cost': 1.5}]
Instead of creating two different items the output just repeats the most recent one I entered. I am making some basic semantic error and I can't figure out how to populate the "grocery_history" list with different items from the user input loop. I tried using pythontutor.com for help but was just berated for being stupid. Any help is appreciated.
Try doing this:
grocery_item = dict()
grocery_history = []
choice = 0
stop = True
while stop == True:
current_item = dict()
current_item['name'] = str(input('Item name: '))
current_item['quantity'] = int(input('Amount purchased: '))
current_item['cost'] = float(input('Price per item: '))
grocery_history.append(current_item)
choice = str(input('Press c to continue or q to quit'))
if choice == 'c':
stop = True
else:
stop = False
print(grocery_history)
By creating a new dictionary in each loop you'll avoid the duplicate error that you're seeing.
You should move the current_item dictionary into the while, for example:
while True:
current_item = {}
# accepts user inputs here
grocery_history.append(current_item)
choice = str(input('Press c to continue or q to quit'))
if choice != 'c':
break
Some other notes:
No need to initiate choice = 0 before the loop.
Use break to stop the loop as soon as possible without going back to check the condition again
You're getting this because dictionaries in Python are mutable objects: this means that you can actually modify their fields without creating a brand new one.
Follow this link if you want to understand more deeply what are the main differences between mutable and immutable objects.
This is your code slightly modified, and working:
grocery_history = []
while True:
name = input('Item name: ').strip()
quantity = int(input('Amount purchased: '))
cost = float(input('Price per item: '))
current_item = {'name':name, 'quantity':quantity, 'cost':cost}
grocery_history.append(current_item)
choice = str(input('Press c to continue or q to quit: '))
if choice == 'q':
break
print(grocery_history)