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)
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.
#bll
class cms():
def __init__(self):
self.namelist = []
self.idlist = []
self.moblist = []
self.emaillist = []
self.reslist = []
def addcustomer(self):
self.idlist.append(id)
self.namelist.append(name)
self.moblist.append(mob)
self.emaillist.append(email)
return print("Customer Added")
def showcustomer(self):
print(self.idlist, self.namelist, self.moblist, self.emaillist)
#pl
while(1):
print("Enter Your Choice Enter 1 to Add, 2 to search, 3 to delete, 4 to Modify, 5 to Display All, 6 to Exit")
ch = input("Enter your choice")
conman = cms()
if ch == '1':
id = input("ENter your id")
name = input("Enter Your name")
mob = input("Enter your mobile no")
email = input("Enter your email")
conman.addcustomer()
elif ch == '2':
conman.showcustomer()
this is my code when I am entering 1 then the customer gets added,but when I call another method to print that appended item it returns blank list
Output:-
Enter your choice2
[] [] [] []
Help!! Please.
conman = cms()
Because this is inside the loop, each time through the loop, this creates a separate, new cms with its own lists of data, and makes conman be a name for the new value.
elif ch == '2':
conman.showcustomer()
This, therefore, displays information from the new conman, ignoring everything that was done in the previous iteration of the loop.
Is there a way when asking the program to chose a random entry from a dictionary of key-value entries is there a way that once every entry has been picked once the program will let the user know that all entries have been picked and then stop, ultimately only allowing each entry to be picked once so, if there are only 3 entries the program will only run 3 times and if there are 100 entries it will run 100 times and so on? New to python coding so please bear with me.
from random import *
def show_keys():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(keys))
print('Define: ', random_key)
input('Press return to see the definition')
print(keys [random_key])
# Set up the keys
keys = {'key1':'definition1',
'key2':'definition2',
'key3':'definition3'}
# The loop
exit = False
while not exit:
user_input = input('Enter s to show a key, or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_keys()
else:
print('You need to enter either q or s.')
You can get the keys from the dictionary, select random elements from that list, get the dictionary entry and remove the key from the list subsequently.
import random
dictionary = {
'one': '1',
'two': '2',
'three': '3'
}
# getting list of keys from dictionary
keys = list(dictionary.keys())
print(keys)
# picking random elemt from list
elem = random.choice(keys)
print(elem, dictionary.get(elem))
# remove an element from a list
keys.remove(elem)
print(keys)
Use a set to collect which keys you aready asked for.
Provide the set and the dict to the function that asks for a definition so it can add a new key to it - do not use globals.
Loop until either no more guesses possible (len(already)==len(data)) and handle that case or until user wants to quit:
from random import choice # do not import ALL - just what you need
def show_keys(d,a): # provide data and already used key set
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
d : your dict of keys and definitions
a : a set of already used keys
"""
# choice only for those keys that are not yet used
random_key = choice( [k for k in d if k not in a] )
print('Define: ', random_key)
input('Press return to see the definition')
print(d [random_key])
# add used key to a - you could ask (y/n) if the definition was correct
# and only then add the key - if wrong it has a chance of being asked again
a.add(random_key)
# Set up the data with keys and defs
data = {'key1':'definition1',
'key2':'definition2',
'key3':'definition3'}
# set up already seen keys
already = set()
# The loop
while True: # loop until break
# nothing more to guess
if len(already)==len(data):
y = input("Game over. Play again? [y, ]").lower()
if y=="y":
# reset set of seen stuff to empty set()
already = set()
else:
break
user_input = input('Enter s to show a key, or q to quit: ')
if user_input == 'q':
break
elif user_input == 's':
# provide data and already to the function, don't use globals
show_keys(data,already)
else:
print('You need to enter either q or s.')
Alternativly: create a shuffled list and use that:
from random import shuffle
data = {'key1':'definition1',
'key2':'definition2',
'key3':'definition3'}
already = set()
shuffled = list(data.items())
shuffle(shuffled)
# The loop
while shuffled:
user_input = input('Enter s to show a key, or q to quit: ')
if user_input == 'q':
break
elif user_input == 's':
key,value = shuffled.pop()
print('Define: ', key)
input('Press return to see the definition')
print(value)
else:
print('You need to enter either q or s.')
I'm working on a school project and I have a problem. I have to write code for apothecary where clients can buy medicine. So, I need to make restrictions, which one doesn't go with others and etc. Here is the code:
def prodajLek():
lekovi = Fajl1.UcitavanjeLekova()
lekoviRed = []
brojacZaForPetlju = 1
n = 0
cena = 0
kolicina = []
korpa = []
rednibrojevilekova = []
ukupnacena = 0
print(" Fabricki naziv Genericki naziv Serijski broj Kolicina Cena \n")
for i in lekovi:
x = i.strip().split("|")
lekoviRed.append(x)
if lekoviRed[n][5] == "False":
print(brojacZaForPetlju,"\t {:10} \t {:10} \t\t\t {:3} \t\t\t {:4} \t\t {:5}".format(x[0],x[1],x[2],x[3],x[4]))
brojacZaForPetlju = brojacZaForPetlju + 1
n = n + 1
print("\n\n\n\n")
rednibrleka = input("Izaberite redni broj leka koji zelite da prodate:\n>>\t")
rednibrleka = int(rednibrleka)
rednibrleka = rednibrleka - 1
rednibrojevilekova.append(rednibrleka)
kolicinaZahteva = input("Koju kolicinu zelite da prodate?\n>>\t")
kolicinaZahteva = int(kolicinaZahteva)
if kolicinaZahteva > int(lekoviRed[rednibrleka][3]):
print("Nema toliko na lageru!\n")
Fajl1.LekarMenu()
kolicina.append(kolicinaZahteva)
cena = int(lekoviRed[rednibrleka][4])
korpa.append(cena)
print("Da li zelite da kupite jos lekova?\n1.Da\n2.Ne\n")
nastavakKupovine = input(">>")
if nastavakKupovine == "1":
prodajLek()
elif nastavakKupovine == "2":
Fajl1.LekarMenu()
So, when I get to the nastavakKupovine input, when I press 1, I need to continue shopping and store my row numbers, my price and quantity in arrays rednibrojlekova = [] , korpa = [] and kolicina = []. But I have a problem, because I dont know how to continue this without reseting these arrays to empty.
The standard idiom for what you want to do is a while True loop. Rather than show how to change your (rather long) function, here's a very simple one which hopefully shows the principle in a straightforward way:
def ask():
answers = []
while True:
response = input("What do you have to say? ")
answers.append(response)
check = input("Type 'q' to quit, anything else to repeat: ")
if check == "q":
break
else:
continue
return answers
For this simple function, the else: continue part isn't necessary, because the loop will continue anyway, but I've included it so you can see how to use it.
Here's an example of the function in action:
>>> ask()
What do you have to say? Something
Type 'q' to quit, anything else to repeat:
What do you have to say? Another thing
Type 'q' to quit, anything else to repeat:
What do you have to say? Ok, done
Type 'q' to quit, anything else to repeat: q
['Something', 'Another thing', 'Ok, done']
>>>
You can find out more about while, break and continue by reading the More Control Flow Tools chapter of the official Python tutorial.
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()