Okay, so I'm kind of lost here. I understand how to insert a value into the code myself [Example - x.insert(2, 99)] but what I'm getting hung up on is what happens if I'm trying to get the user to tell me where they want the item to be in regards to position in the list.
Example
inventory = [dagger, sword, shield, breastplate, helmet]
this is what I have and I know it doesn't work.
def edit_it():
inventory = ["orb", "staff", "spellbook", "hat", "potion", "robe"]
inventory[item] = input("Number: ")
print(inventory)
I just want it to show an updated position list if the user wanted to move say, the spellbook to the front, thus pushing back all other items. I've been at this all day and I'm spent. Help?
After reading the item and new index for the item as a number, find it in the list, pop it, and insert it into the list at that index.
def edit_it():
inventory = ["orb", "staff", "spellbook", "hat", "potion", "robe"]
item = input("Which item do you want to move? ")
new_index = int(input("Number: "))
inventory.insert(new_index, inventory.pop(inventory.index(item)))
print(inventory)
How about something like this:
item= int(input("Number: "))
inventory.insert(0,inventory.pop(item))
*This works on python 2, and python 3
Related
this is a follow up from my previous question where I am working on multiple dictionary and having trouble with them. I have currently have a main dictionary where I store my data and one blank dictionary where I add data into.
Dairy_goods = {1:{'item':'Milk','p':2.47,'g':0.16,'offer':'Yes'},
2:{'item':'Butter','p':4.50,'g':0.32,'offer':'No'},
3:{'item':'Egg','p':3.40,'g':0.24,'offer':'No'}}
shopping_basket={}
Lets say for example I would like to add the item "Milk" into the blank shopping basket, i would do as below.
choose=int(input('1.Item= Milk, Price= $2.47, GST= $0.16, Offer=Yes\n'
'2.item= Butter, Price= $4.50, GST= $0.32, Offer=No\n'
'3.Item= Egg, Price= $4.50, GST= $0.32, Ofer=No\n'
'Enter your option: '))
qnty=int(input('How many do you want?: '))
shopping_basket[Dairy_goods[choose]['item']] = shopping_basket.get(Dairy_goods[choose]['item'], 0) + qnty,Dairy_goods[choose]['p'],Dairy_goods[choose]['g'],Dairy_goods[choose]['offer']
I would get an output as below.
print(shopping_basket)
{'Milk': (2, 2.47, 0.16, 'Yes')}
Now I would like to edit the values inside of this new dictionary, how do I go about doing so? As it has no fix key? I am aware it it is in a tupple and can convert to a list but will still give a error as shown below.
for item in shopping_basket:
item = str(input('key in an item to edit: '))
for item in shopping_basket:
shopping=list(shopping_basket)
qnty = int(input('Key in the quantity of %s you want: ' % item))
shopping[item][0] = qnty # i would get a error here.
print(shopping)
Let me know if more clarifications is needed, thank you in advance.
There are a few things off in your code in terms of data structures. First, a dictionary with incrementing keys {1: ..., 2: ..., ...} is basically the same as a list, so you can just as well use the simpler data structure and select items by indexing. The only thing to note here is that list indices start at 0, so you need to subtract 1 from your user's choice.
Dairy_goods = [{'item':'Milk','p':2.47,'g':0.16,'offer':'Yes'},
{'item':'Butter','p':4.50,'g':0.32,'offer':'No'},
{'item':'Egg','p':3.40,'g':0.24,'offer':'No'}]
choose = int(input('1.Item = ... ')) - 1 # subtract 1 to get 0-indexing
qnty = int(input('How many do you want?: '))
Next up, there is a lot going on in the line shopping_basket[Dairy_goods[choose]['item']] = ..., which makes it hard to work with. In my comment, I suggested to go for dictionaries to store the items in the shopping basket to make them easier to modify. The new format of the basket would look like
# shopping_basket
{'Milk':{'item':'Milk','p':2.47,'g':0.16,'offer':'Yes', 'qnty':1}}
which is a bit redundant because of the double item name (as key and within values), which is normally considered a bad thing, but in this case it allows for a much easier access to the shopping cart items.
However, it's actually sufficient to store only the quantities in the shopping basket - {'Milk':1, 'Egg':2, ...} - because all the other information is in Dairy_goods.
selection = Dairy_goods[choose] # e.g., {'item':'Milk','p':2.47,'g':0.16,'offer':'Yes'}
item = selection['item'] # e.g., 'Milk'
shopping_basket[item] = shopping_basket.get(item, 0) + qnty
# optional: delete item if the quantity is <= 0
if shopping_basket[item]['qnty'] <= 0:
shopping_basket.pop(item)
Then, the edit part becomes:
item = input('key in an item to edit: ') # e.g., 'Milk'
qnty = int(input(f'Key in the quantity of {item} you want: ')) # did you hear about f-strings? Super useful!
shopping_basket[item] = qnty # set the new quantity
I have your answer!
But first I want to address a major problem in your code:
for shopItem in shopping_basket:
item = str(input('key in an item to edit: '))
for item in shopping_basket: # unneeded
shopping=list(shopping_basket)
qnty = int(input('Key in the quantity of %s you want: ' % shopItem))
shopping[shopItem][0] = qnty # i would get a error here.
print(shopping)`
That internal for loop can be easily remove to get cleaner code.
for shopItem in shopping_basket:
item = str(input('key in an item to edit: '))
shopping=list(shopping_basket)
qnty = int(input('Key in the quantity of %s you want: ' % shopItem))
shopping[shopItem][0] = qnty # i would get a error here.
print(shopping)`
Now for the actual problem:
for shopItem in shopping_basket:
item = str(input('key in an item to edit: '))
shopping = list(shopping_basket[shopItem])
qnty = int(input('Key in the quantity of %s you want: ' % shopItem))
shopping[item] = qnty # Fixed
Originally with this line of code
shopping=list(shopping_basket) you were changing {'Milk': (2, 2.47, 0.16, 'Yes')} to ['Milk'], and then attempting to change a letter in the word milk, which was throwing an error. I fixed that by changing shopping[item][0] to shopping[item].
Have a great day and good luck with your code!
I am trying to use a while loop to keep asking which item to remove from a list until the user enters an existing index in python. Basically when the user is asked, "What item would you like to remove?" the user should be able to enter a number starting from 1 instead of zero, and up to whatever number of items, there are. For example, if there are ten items, the user should be able to enter 1 -10, not 0 - 9. I have already converted the user input to a zero-based index. Now I need to be able to keep asking "What item would you like to remove?" until the user inputs an existing index.
Here is the code that I am getting stuck on:
items = []
prices = []
quantities = []
item = input("\nWhat item would you like to remove? ").strip()
while item != range(0, len(items)):
print("\nSorry, that is not a valid number.")
item = input("\nWhat item would you like to remove? ").strip()
item_remove = items[int(item) - 1]
items.pop(int(item) - 1)
prices.pop(int(item) - 1)
quantities.pop(int(item) - 1)
print(item_remove + " removed.")
break
I shortened the code so you wouldn't have to read as much, but here is what is happening. When I put in an existing index it displays the print statement "Sorry, that is not a valid number." and then asks for the input "What item would you like to remove?" a second time then after you enter an existing index again it removes the item and goes back to the main menu option that I am using in my code. However, if you enter an index that does not exist, it displays the print statement "Sorry, that is not a valid number." then asks "What item would you like to remove?", but the second time that I enter an index that does not exist the code crashes saying list index out of range. Is there any way that I could get this code to keep asking "What item would you like to remove?" followed by the print statement "Sorry, that is not a valid number." until I enter an existing index? If you need more code let me know, and I greatly appreciate any help or feedback.
I have been studying Python and trying to create a simple telephone book. However, I can't solve how to delete an item by using an index. Here is the code that doesn't work:
number = 1
while number < len(book):
for x in book:
print("{}) NAME: {} NUMBER: {} ".format(number,x,book[x]))
number = number + 1
delete = input("Insert the number you want to delete\n")
delete = int(delete)
book.pop(delete - 1)
This code can successfully list all of the contact information in the phone book, but I cannot find any way to delete the items. I think it'd be impractical to insert the name of the person whom you want to delete.
Is there any alternative that I can do? Thank you so much.
Asuming book is a list, you can delete elements
by index with del book[index]
by element reference with book.remove(delete)
If I understood correctly what you want to do:
book=[("NAME1",2313),("NAME2",65345313),("NAME3",1112313),("NAME4",151377)]
while book:
for x in range(len(book)):
print("{}) NAME: {} NUMBER: {} ".format(x,book[x][0],book[x][1]))
book.pop(int(input("Insert the number you want to delete:")))
hopefully there is a simple answer for this. How can I take user input from a while loop and print all of the input (without using lists when writing this)? Is there a way to output this information when the number of executions from the user is unknown? I am only a beginner so if there is a simple way to do this just using basics please let me know!
Here is an example of what I am trying to ask:
Say I am asking the user for the name and price of an item. They have the option to enter more items, or stop the execution. Then the output would list the name of the items, the prices, and their total amount purchased. I would like to print out all of these items that they have inputted.
Output formatted something like this:
Item Name Item Price
Soap $ 3.98
Detergent $ 6.99
Chips $ 2.50
....
....
Your Total: $xx.xx
I know how to do everything else, just having issues displaying all of their given input after they stop the execution. Just needing some guidance in this area. Please let me know if there is anything I can clarify. Thanks in advance!
I am using Python 3.
So I hope this matches what you were asking for.
I used nested dictionries, incase you want more info per item, but I mean you can also use tuples if you want.
prompts = ["Item name", "Item price"]
flag = True
items = {}
indx = 0
while flag:
inp = input("Type 'new' to register a new item or 'exit' to exit ")
if inp == "new":
output = {}
for p in prompts:
inp = input(p)
output[p] = inp
indx += 1
items[indx] = output
if inp == "exit":
flag = False
This is fairly simple, but to explain the steps;
Typing new allows you to start entering a new item.
It asks the prompts that are listed in the prompts list.
(It also uses these prompts to name the values in the output dict)
Once all the data is in, it'll be indexed and added into the items dict.
Then the loop begins again. You can add the new item, or type exit to stop entering items.
Edit:
Also I decided to use a flag instead of breaks so you can modify if you want more stop conditions.
I didn't understand so well but I think you can use:
bill = ''
total_price = 0
while True:
item = input('(If Done Write Exit) Item Name: ')
if item == "exit":
break
price = input("price: ")
bill = bill + "Item: "+item + '\nPrice: ' + price + '\n\n'
total_price += int(price)
print('\n'*4)
print(bill+'\n\nTotal Price:',total_price)
I am a novice, just started learning how to program.
I will to ask how do I get the frequency/count of a value changed within a key?
for instance:
user_input= input("Enter a word")
dict = {"Coffee": ["I love coffee."], "Tea": ["I love tea."]}
so if the user selects coffee, he/she can amend by adding or delete that value.
He/she is then able to view the number of time the key "coffee" is being amended.
I appreciate the prompt responses from everyone! But maybe this example below will be a little more comprehensive.
if user selects coffee, they can either have the option to delete or append new sentence to the existing key.
So for every value that is being deleted or added: it will be recorded
For example: If I will to change the Coffee's value, that will 1, thereafter, if I will to delete the Coffee's value again, it will be the 2nd time I have amend the value within coffee.
output: Revision changed on "Coffee" : 2
I'm not sure if I'm understanding your question correctly, but if I am, then an if statement should do the trick, every time the user picks coffee it'll add one to it's corresponding counter and same thing with tea, then you do whatever you want with those values:
user_input= input("Enter a word")
dict = {"Coffee": ["I love coffee."], "Tea": ["I love tea."]}
if user_input == "Coffee":
coffee_amend += 1
if user_input == "Tea":
tea_amend += 1
This is my first time ever responding to anything so please tell me if I did anything wrong; I hope you found this helpful!
First modify the structure of the dictionary that you are using like below:
dic = {"Coffee": [["I love coffee."],0], "Tea": [["I love tea."],0]}
As you can see I have maintained, the count of number of times changed and It value at the key.
Now make two functions for changing the value at a particular key and getting the count of number of times value changed at that particular key
def changeKeyValue(dic, key, value):
dic[key][1] += 1
dic[key][0] = value
changeKeyValue(dic,'Coffee',None)
def getNumTimes(dic,key):
return dic[key][1]
Now use these functions to get the result you want :
print("Key value changed", getNumTimes(dic,"Coffee"))
Hope this helped.
I am assuming that you want something that interacts with the user. This is not super elegant but it is easy to understand:
dict = {"Coffee": ["I love coffee."], "Tea": ["I love tea."]}
cnt_dict = {}
cont = True
while cont == True:
user_input = input("Enter a word")
user_input2 = input('What would you like to do?')
if user_input2 == 'delete':
dict[user_input] = '' #sets the value to empty list
if user_input2 == 'ammend':
user_input3 = input('What would you like to change to?')
dict[user_input] = user_input3
if user_input in cnt_dict.keys():
cnt_dict[user_input] += 1
else:
cnt_dict[user_input] = 1
print(cnt_dict)
input_4 = input('continue? (y/n)')
if input_4 != 'y':
cont = False
cnt_dict is a dictionary which counts the number of times each key is changed. Hopefully this helps. Edit: Obviously there will be problems if you are trying to add things not currently in dict but you can build off this.