This question already has an answer here:
How to create a counter that counts unrighteous inputs
(1 answer)
Closed 2 months ago.
I need to put this code in a loop so that you can choose whichever number first and go back to the start after whichever one you choose, but everything I've tried hasn't worked and need help.
peoples = {
"Mary": {
"name": "Mary",
"budget": 100,
"items": {
"Game": 0,
"Book": 0,
"Kindle": 0
},
"status": "incomplete"
},
"Steve": {
"name": "Steve",
"budget": 100,
"items": {
"Tie": 0,
"Scarf": 0,
"Amazon Echo": 0
},
"status": "incomplete"
},
"Kevin": {
"name": "Kevin",
"budget": 65,
"items": {
"Mario Kart": 0
},
"status": "incomplete"
},
"Jane": {
"name": "Jane",
"budget": 50,
"items": {
"Gift Card": 0,
"Gloves": 0
},
"status": "incomplete"
},
"Chris": {
"name": "Chris",
"budget": 100,
"items": {
"Chocolates": 0,
"Galaxy Tab": 0
},
"status": "incomplete"
}
}
print("""
Menu
--------------------
1. Update Shopping List
2. Complete Shopping List
3. Display Shopping List
4. Exit Application
--------------------
Make your selection
""")
option = int(input("Enter an option: "))
if option == 1:
people = input("Who are you updating?: ")
print("\nCurrent values of people",people)
print(peoples[people])
print("\nAvailable items and their prices are:")
for item in peoples[people]["items"]:
print(item, peoples[people]["items"][item])
item_to_update = input("Enter an item to update: ")
price = int(input("Enter updated price: "))
budget = peoples[people]["budget"] - peoples[people]["items"]
[item_to_update] - price
peoples[people]["items"][item_to_update] = price
peoples[people]["budget"] = budget
print("\nUpdated values of people",people)
print(peoples[people])
option = int(input("\nEnter an option: "))
if option == 2:
update = input("Choose one of the 5 people to complete their shopping list: ")
if update in peoples:
print("You have chosen",update)
answer = input("Do you want to complete their shopping list (Y/N)? ")
if answer.upper() == "Y":
peoples[people]['status'] = 'complete'
print("Shopping list has been completed!")
option = int(input("\nEnter an option: "))
if option == 3:
display = input("Who's do you want to look at?: ")
print("\nShopping List Of",display)
print(peoples[display])
option = int(input("\nEnter an option: "))
if option == 4:
print("Thank You For Shopping With Us!")
I've tried putting in different versions of loop, but it always either results in the program ignoring it and not going back to the start, or breaking when I choose something else then 1 at the start.
option = input("Enter an option: ")
if option == "1":
people = input("\nWho are you updating?: ")
print("\nCurrent values of people",people)
print(peoples[people])
print("\nAvailable items and their prices are:")
for item in peoples[people]["items"]:
print(item, peoples[people]["items"][item])
item_to_update = input("Enter an item to update: ")
price = int(input("Enter updated price: "))
budget = peoples[people]["budget"] - peoples[people]["items"][item_to_update] - price
peoples[people]["items"][item_to_update] = price
peoples[people]["budget"] = budget
print("\nUpdated values of people",people)
print(peoples[people])
elif option == "2":
update = input("Choose one of the 5 people to complete their shopping list: ")
if update in peoples:
print("You have chosen",update)
peoples[people]['status'] = 'complete'
print("Shopping list has been completed!")
elif option == "3":
display = input("Who's do you want to look at?: ")
print("\nShopping List Of",display)
print(peoples[display])
elif option == "4":
print("Thank You For Shopping With Us!")
break
else:
print("That's not a valid answer! Try again!")
With the same list above, After adding in my information to the set example given, I would get the error below.
error with pic: https://i.stack.imgur.com/BrqBB.png
peoples = {
"Mary": {
"name": "Mary",
"budget": 100,
"items": {
"Game": 0,
"Book": 0,
"Kindle": 0
},
"status": "incomplete"
},
"Steve": {
"name": "Steve",
"budget": 100,
"items": {
"Tie": 0,
"Scarf": 0,
"Amazon Echo": 0
},
"status": "incomplete"
},
"Kevin": {
"name": "Kevin",
"budget": 65,
"items": {
"Mario Kart": 0
},
"status": "incomplete"
},
"Jane": {
"name": "Jane",
"budget": 50,
"items": {
"Gift Card": 0,
"Gloves": 0
},
"status": "incomplete"
},
"Chris": {
"name": "Chris",
"budget": 100,
"items": {
"Chocolates": 0,
"Galaxy Tab": 0
},
"status": "incomplete"
}
}
print("""
Menu
--------------------
1. Update Shopping List
2. Complete Shopping List
3. Display Shopping List
4. Exit Application
--------------------
Make your selection
""")
while True:
option = input("Enter an option: ")
if option == "1":
people = input("\nWho are you updating?: ")
print("\nCurrent values of people",people)
print(peoples[people])
print("\nAvailable items and their prices are:")
for item in peoples[people]["items"]:
print(item, peoples[people]["items"][item])
item_to_update = input("Enter an item to update: ")
price = int(input("Enter updated price: "))
budget = peoples[people]["budget"] - peoples[people]["items"][item_to_update] - price
peoples[people]["items"][item_to_update] = price
peoples[people]["budget"] = budget
print("\nUpdated values of people",people)
print(peoples[people])
elif option == "2":
update = input("Choose one of the 5 people to complete their shopping list: ")
if update in peoples:
print("You have chosen",update)
peoples[people]['status'] = 'complete'
print("Shopping list has been completed!")
elif option == "3":
display = input("Who's do you want to look at?: ")
print("\nShopping List Of",display)
print(peoples[display])
elif option == "4":
print("Thank You For Shopping With Us!")
break
else:
print("That's not a valid answer! Try again!")
It now looks exactly like this, and it still gives back a syntax error on the first elif statement. I don't understand what the problem is if it's properly indented and should follow the correct rules to use it.
edited with error: https://i.stack.imgur.com/rTW6k.png
The syntax error is finally gone, but now lies the problem where the code just repeats itself on the menu screen without going anywhere, like this:
repeating: https://i.stack.imgur.com/YNPdF.png
I would do something like this:
while True:
print(<instructions>)
option = input("Enter an option: ")
if option == "1":
do stuff...
elif option == "2":
do number two stuff..
elif option == "3":
do that third stuff..
elif option == "4":
print("Thank You For Shopping With Us!")
break
else:
print("That's not a valid answer! Try again!")
This will keep the menu in a loop and if option 4 is selected, it will break from the loop and continue on.
The issue now is with your indentation. You must indent your code properly for python to be able to understand what you want it to do, for instance:
x= "3"
if x == "2":
print("hello world")
print("outside the indent")
you console output would be:
>>outside the indent
but if your code looks like this:
x= "3"
if x == "2":
print("hello world")
print("outside the indent")
you would get no output from the console, everything is within the "if" code block. Indentation is crucial for python to exhibit the expected behavior. you need to make sure that all your code for each condition is indented properly inside the if blocks, like the example I gave above. Also, if you want this in a loop, you need to put it in a loop with the while True: statement, and indent everything inside it.
Your final result should look something like this:
peoples = {
"Mary": {
"name": "Mary",
"budget": 100,
"items": {
"Game": 0,
"Book": 0,
"Kindle": 0
},
"status": "incomplete"
},
"Steve": {
"name": "Steve",
"budget": 100,
"items": {
"Tie": 0,
"Scarf": 0,
"Amazon Echo": 0
},
"status": "incomplete"
},
"Kevin": {
"name": "Kevin",
"budget": 65,
"items": {
"Mario Kart": 0
},
"status": "incomplete"
},
"Jane": {
"name": "Jane",
"budget": 50,
"items": {
"Gift Card": 0,
"Gloves": 0
},
"status": "incomplete"
},
"Chris": {
"name": "Chris",
"budget": 100,
"items": {
"Chocolates": 0,
"Galaxy Tab": 0
},
"status": "incomplete"
}
}
print("""
Menu
--------------------
1. Update Shopping List
2. Complete Shopping List
3. Display Shopping List
4. Exit Application
--------------------
Make your selection
""")
while True:
option = input("Enter an option: ")
if option == "1":
people = input("\nWho are you updating?: ")
print("\nCurrent values of people",people)
print(peoples[people])
print("\nAvailable items and their prices are:")
for item in peoples[people]["items"]:
print(item, peoples[people]["items"][item])
item_to_update = input("Enter an item to update: ")
price = int(input("Enter updated price: "))
budget = peoples[people]["budget"] - peoples[people]["items"][item_to_update] - price
peoples[people]["items"][item_to_update] = price
peoples[people]["budget"] = budget
print("\nUpdated values of people",people)
print(peoples[people])
elif option == "2":
update = input("Choose one of the 5 people to complete their shopping list: ")
if update in peoples:
print("You have chosen",update)
peoples[people]['status'] = 'complete'
print("Shopping list has been completed!")
elif option == "3":
display = input("Who's do you want to look at?: ")
print("\nShopping List Of",display)
print(peoples[display])
elif option == "4":
print("Thank You For Shopping With Us!")
break
else:
print("That's not a valid answer! Try again!")
Also, please review this link as it is crucial you understand how to properly indent your code when writing python.
https://www.geeksforgeeks.org/indentation-in-python/
Related
I have a line like this and I need to convert it to json format
{from:[3,4],to:[7,4],color:2},{from:[3,6],to:[10,6],color:3},{from:[5,8],to:[9,8],color:5},{from:[5,11],to:[10,11],color:6},{from:[1,0],to:[1,11],color:0},{from:[10,1],to:[10,6],color:4},{from:[3,0],to:[8,0],color: 1}
Applying this code, I will transform it, but not completely, as I need
def select(value):
ll = value.split(',{')
ll = [element.replace("{", '') for element in ll]
ll = [element.replace("}", '') for element in ll]
js = {str(i):letter for i,letter in enumerate(ll)}
js = json.dumps(js)
return js
total["data_words_selection"] = total["data_words_selection"].map(lambda x: str(x).lstrip("['").rstrip("']")).astype(str)
total['data_words_selection'] = total['data_words_selection'].apply(select)
I receive it like this:
{
"0": "from:[3,4],to:[7,4],color:2",
"1": "from:[3,6],to:[10,6],color:3",
"2": "from:[5,8],to:[9,8],color:5",
"3": "from:[5,11],to:[10,11],color:6",
"4": "from:[1,0],to:[1,11],color:0",
"5": "from:[10,1],to:[10,6],color:4",
"6": "from:[3,0],to:[8,0],color:1"
}
I get valid json. Please tell me how can I convert this string to this format:
{
"0":
"from":
"0": "3"
"1": "4"
"to":
"0": "7"
"1": "4"
"color": "2"
"1":
"from":
"0": "3"
"1": "6"
"to":
"0": "10"
"1": "5"
"color": "3"
}
The result, which I would like to see, was written by hand, sorry for the mistakes. please tell me
This is an example of what it should look like. I hope you understand what I want
As other guys said. It is not perfectly clear what you want to do. But maybe this code can help you:
import json
import re
input_ = "{from:[3,4],to:[7,4],color:2},{from:[3,6],to:[10,6],color:3},{from:[5,8],to:[9,8],color:5},{from:[5,11],to:[10,11],color:6},{from:[1,0],to:[1,11],color:0},{from:[10,1],to:[10,6],color:4},{from:[3,0],to:[8,0],color:1}"
def parse_json(input_):
arr = input_.split("},")
arr = [x+"}" for x in arr]
arr[-1] = arr[-1][:-1]
return json.dumps({str(i):add_quotation_marks(x) for i, x in enumerate(arr)})
def add_quotation_marks(input_):
words = re.findall(r'(\w+:)', input_)
for word in words:
input_ = input_.replace(word[:-1], f'"{word[:-1]}"')
return json.loads(input_)
print(parse_json(input_))
List stay as list, but it could be transformed into dict.
I'm working on a vending machine program and my code skips straight to the else statement instead of taking the user input and comparing it to the ID number in the list.
Here's the list and code:
`
itemstock = [
{
"idnum": 0,
"name": 'Water',
"price": 12,
},
{
"idnum": 1,
"name": 'Soda',
"price": 14,
},
{
"idnum": 2,
"name": 'Juice',
"price": 13,
},
]
choice = int(input("Now, choose an item ID from the Menu and enter the ID: "))
for i in itemstock:
if choice in ["idnum"]:
print("You have chosen item", choice)
else:
print("This is not a valid ID.")
break
`
I had hoped for if I had input the number 2, it would display what the user chose along with some text but it skips straight to the else statement. I've tried looking online but I may be doing something wrong here.
if choice in ["idnum"]
That is just a list containing the text "idnum". You want i["idnum"] instead:
for i in itemstock:
if i["idnum"] == choice:
print("You have chosen item", choice)
break
else:
print("This is not a valid ID.")
I also moved the else block out one level, so it is paired with the for loop, not the if statement. When a for loop iterates all the way to the end, the else block is executed (if it has one).
For a project I'm creating an online library system. Now, I have loaded the books and all their info with a json file. The json file looks something like this:
[
{
"author": "Unknown",
"country": "Sumer and Akkadian Empire",
"imageLink": "images/the-epic-of-gilgamesh.jpg",
"language": "Akkadian",
"link": "https://en.wikipedia.org/wiki/Epic_of_Gilgamesh\n",
"pages": 160,
"title": "The Epic Of Gilgamesh",
"ISBN": "978123438397",
"year": -1700
},
{
"author": "Unknown",
"country": "Achaemenid Empire",
"imageLink": "images/the-book-of-job.jpg",
"language": "Hebrew",
"link": "https://en.wikipedia.org/wiki/Book_of_Job\n",
"pages": 176,
"title": "The Book Of Job",
"ISBN": "9781238427897",
"year": -600
},
{
"author": "Unknown",
"country": "India/Iran/Iraq/Egypt/Tajikistan",
"imageLink": "images/one-thousand-and-one-nights.jpg",
"language": "Arabic",
"link": "https://en.wikipedia.org/wiki/One_Thousand_and_One_Nights\n",
"pages": 288,
"title": "One Thousand and One Nights",
"ISBN": "9781234564897",
"year": 1200
},
{
"author": "Unknown",
"country": "Iceland",
"imageLink": "images/njals-saga.jpg",
"language": "Old Norse",
"link": "https://en.wikipedia.org/wiki/Nj%C3%A1ls_saga\n",
"pages": 384,
"title": "Nj\u00e1l's Saga",
"ISBN": "9781234566827",
"year": 1350
},
{
"author": "Jane Austen",
"country": "United Kingdom",
"imageLink": "images/pride-and-prejudice.jpg",
"language": "English",
"link": "https://en.wikipedia.org/wiki/Pride_and_Prejudice\n",
"pages": 226,
"title": "Pride and Prejudice",
"ISBN": "9781234955897",
"year": 1813
},
{
"author": "Honor\u00e9 de Balzac",
"country": "France",
"imageLink": "images/le-pere-goriot.jpg",
"language": "French",
"link": "https://en.wikipedia.org/wiki/Le_P%C3%A8re_Goriot\n",
"pages": 443,
"title": "Le P\u00e8re Goriot",
"ISBN": "9781234525797",
"year": 1835
},
{
"author": "Samuel Beckett",
"country": "Republic of Ireland",
"imageLink": "images/molloy-malone-dies-the-unnamable.jpg",
"language": "French, English",
"link": "https://en.wikipedia.org/wiki/Molloy_(novel)\n",
"pages": 256,
"title": "Molloy, Malone Dies, The Unnamable, the trilogy",
"ISBN": "9781234767747",
"year": 1952
},
{
"author": "Giovanni Boccaccio",
"country": "Italy",
"imageLink": "images/the-decameron.jpg",
"language": "Italian",
"link": "https://en.wikipedia.org/wiki/The_Decameron\n",
"pages": 1024,
"title": "The Decameron",
"ISBN": "9781235622297",
"year": 1351
},
{
"author": "Jorge Luis Borges",
"country": "Argentina",
"imageLink": "images/ficciones.jpg",
"language": "Spanish",
"link": "https://en.wikipedia.org/wiki/Ficciones\n",
"pages": 224,
"title": "Ficciones",
"ISBN": "9781234562237",
"year": 1965
},
{
"author": "Emily Bront\u00eb",
"country": "United Kingdom",
"imageLink": "images/wuthering-heights.jpg",
"language": "English",
"link": "https://en.wikipedia.org/wiki/Wuthering_Heights\n",
"pages": 342,
"ISBN": "9781234567897",
"title": "Wuthering Heights",
"year": 1847
},
{
"author": "Albert Camus",
"country": "Algeria, French Empire",
"imageLink": "images/l-etranger.jpg",
"language": "French",
"link": "https://en.wikipedia.org/wiki/The_Stranger_(novel)\n",
"pages": 185,
"title": "The Stranger",
"ISBN": "9781234562447",
"year": 1942
}
]
One of the requirements is to be able to add, edit and delete a book in the library system. I tried to program a function which adds a book to the system/json file, but it will append after the squared bracket in the json file. And I need it to append right before the last squared bracket. This is the piece of that is supposed add a book:
def addBook(self):
print("Please fill in the following information:")
author = input("Author: ")
country = input("Country: ")
image = input("Image Link: ")
lang = input("Language: ")
link = input("Link: ")
pages = int(input("Pages: "))
title = input("Title: ")
isbn = input("ISBN: ")
year = int(input("Year: "))
y = { "author": author,
"country": country,
"imageLink": image,
"language": lang,
"link": link,
"pages": pages,
"title": title,
"ISBN": isbn,
"year": year
}
a_file = open("books.json", "a")
json.dump(y, a_file)
a_file.close()
Then I also tried to code a function that can edit the details of a book, but I failed miserably. First there is a feature which searches for the book you want, then I need to find a way to select a book:
def selectCatalogue(self):
os.system('cls')
bookInfo = input("Please fill the author or title of the book in: ")
m = 1
for i in data:
if bookInfo.casefold() in i['author'].casefold():
print('['+ str(m) + '] '+ 'Author: '+ i['author'])
print(' ' + 'Country: ' + i['country'])
print(' ' + 'Image link: ' + i['imageLink'])
print(' ' + 'Language: ' + i['language'])
print(' ' + 'Link: ' + i['link'])
print(' ' + 'Pages: ' + str(i['pages']))
print(' ' + 'Title: ' + i['title'])
print(' ' + 'ISBN: ' + i['ISBN'])
print(' ' + 'Year: ' + str(i['year']))
print(' ')
m = m + 1
if bookInfo.casefold() in i['title'].casefold():
print('['+ str(m) + '] '+ 'Author: '+ i['author'])
print(' ' + 'Country: ' + i['country'])
print(' ' + 'Image link: ' + i['imageLink'])
print(' ' + 'Language: ' + i['language'])
print(' ' + 'Link: ' + i['link'])
print(' ' + 'Pages: ' + str(i['pages']))
print(' ' + 'Title: ' + i['title'])
print(' ' + 'ISBN: ' + i['ISBN'])
print(' ' + 'Year: ' + str(i['year']))
print(' ')
m = m + 1
choice = input("Please enter the number of the book you were looking for: ")
# if choice == m:
# need to find a way to select a book
Then I programmed a function which is supposed to be able to edit details of the book:
def editBook(self):
Catalogue().selectCatalogue()
print("What do you want to edit? ")
print('[1] Author')
print('[2] Country')
print('[3] Image link')
print('[4] Language')
print('[5] Link')
print('[6] Pages')
print('[7] Title')
print('[8] ISBN')
print('[9] Year')
choice = input()
with open("books.json", "r+") as jsonFile:
data = json.load(jsonFile)
if choice == '1':
# with open("replayScript.json", "r+") as jsonFile:
# data = json.load(jsonFile)
data["author"] = input("Please enter the new author name: ")
if choice == '2':
data["country"] = input("Please enter the new country name: ")
if choice == '3':
data["imageLink"] = input("Please enter the new image link: ")
if choice == '4':
data["language"] = input("Please enter the new language: ")
if choice == '5':
data["link"] = input("Please enter the new link: ")
if choice == '6':
data["author"] = int(input("Please enter the new number of pages: "))
if choice == '7':
data["title"] = input("Please enter the new title: ")
if choice == '8':
data["ISBN"] = int(input("Please enter the new ISBN: "))
if choice == '9':
data["year"] = int(input("Please enter the new year: "))
Lastly I need to make a function that can delete books, but I'm clueless.
Is there someone who can help me with this? I would really appreciate it!!
Add : Have a look here, I think they explain quite well why you can't just append a new book to the end of your json.
You have a json with a list of dictionaries. If you want to add or delete a book, just get access to a single list element (which is a dictionary) and remove the element, or in case you want to add a book, load the data, append your new book and dump it back to json:
with open('your_json.json', 'r') as f:
data = json.load(f)
data.append(new_book) #new_book is the dict with the new book information
with open('new_json.json', 'w') as g:
json.dump(data, g)
SelectCatalogue():
You don't need to look twice for book or author, you can do that in one step.
At the end you have a variable choice, where you want to select a book by a number, I guess this is in case you have multiple books by one author and you want to select only one specific? You don't need that m as counter, just use enumerate, so you have a number (which is the list index of the dict) for each book.
def selectCatalogue():
bookInfo = input("Please fill the author or title of the book in: ")
for idx, dic in enumerate(data):
if bookInfo.casefold() in [dic['author'].casefold(), dic['title'].casefold()]:
print('['+ str(idx) + '] '+ 'Author: '+ dic['author'])
print(' ' + 'Country: ' + dic['country'])
print(' ' + 'Image link: ' + dic['imageLink'])
print(' ' + 'Language: ' + dic['language'])
print(' ' + 'Link: ' + dic['link'])
print(' ' + 'Pages: ' + str(dic['pages']))
print(' ' + 'Title: ' + dic['title'])
print(' ' + 'ISBN: ' + dic['ISBN'])
print(' ' + 'Year: ' + str(dic['year']))
print(' ')
choice = int(input("Please enter the number of the book you were looking for: "))
data[choice] # <-- this will get you access to one dict which you can print like above if you want
return choice
I added the return statement because you can use it in the edit_book() function to access the book you want to change information.
Here is the new edit function, which asks for book/author, then the number you want (and stores it), then asks which information you want to change, at the end dump the new json to a json file.
def editBook():
book_idx = selectCatalogue() # you need it to access later when editing information
print("What do you want to edit? ")
print('[1] Author')
print('[2] Country')
print('[3] Image link')
print('[4] Language')
print('[5] Link')
print('[6] Pages')
print('[7] Title')
print('[8] ISBN')
print('[9] Year')
choice = input()
with open("books.json", "r") as jsonFile:
data = json.load(jsonFile)
# data is the whole list of dicts, you want to access one element of the list, book_idx added
if choice == '1':
data[book_idx]["author"] = input("Please enter the new author name: ")
if choice == '2':
data[book_idx]["country"] = input("Please enter the new country name: ")
if choice == '3':
data[book_idx]["imageLink"] = input("Please enter the new image link: ")
if choice == '4':
data[book_idx]["language"] = input("Please enter the new language: ")
if choice == '5':
data[book_idx]["link"] = input("Please enter the new link: ")
if choice == '6':
data[book_idx]["author"] = int(input("Please enter the new number of pages: "))
if choice == '7':
data[book_idx]["title"] = input("Please enter the new title: ")
if choice == '8':
data[book_idx]["ISBN"] = int(input("Please enter the new ISBN: "))
if choice == '9':
data[book_idx]["year"] = int(input("Please enter the new year: "))
#write the edited list of dicts back to json
with open('books_edited.json', 'w') as jsonFile:
json.dump(data, jsonFile)
Regarding your last problem, deleting a book:
As you can see I accessed the dictionary with its list index in the other functions. For this task you just need to call the selectCatalogue() and save the chosen book index to a variable. Then delete that element data[index] and write the new data back to json.
You should be able to get that done by yourself now :)
Since you work in a class and I don't have it, I removed some of the parts to get it running. Don't forget to add it back to it.
I am trying to loop through my list of dictionaries and print out the highest bidder in my list of dictionaries. In a for loop with python is 'i' not automatically an integer?
Example : for i in dictionary:
Does i not equal 0, 1, 2 so on?
bidders = [
{
"name": "nicholas",
"bid": 12,
},
{
"name": "jack",
"bid": 69,
},
]
for i in bidders:
bid = bidders[i]["bid"]
name = bidders[i]["name"]
if bid > bid:
print(f"Congratulations {name}! Your bid of ${bid} wins!")
else:
print(f"Congratulations {name}! Your bid of ${bid} wins!")
You can use enumerate to range through a list and get the current index. Fixing your for loop, it would look like this:
for idx, _ in enumerate(bidders):
bid = bidders[idx]["bid"]
name = bidders[idx]["name"]
No, since you are not calling the range function i is not default a integer. Leonardo's answer looks more correct, however what I wrote down below would also work.
bidders = [
{
"name": "nicholas",
"bid": 12,
},
{
"name": "jack",
"bid": 69,
},
]
maxBid = -1
maxBidName = "";
for i in range(0, len(bidders)):
bid = bidders[i]["bid"]
name = bidders[i]["name"]
if bid > maxBid:
maxBid = bid
maxBidName = name
print(f"Congratulations {maxBidName}! Your bid of ${maxBid} wins!")
there are few mistakes, i think this will works
bidders = [
{
"name": "nicholas",
"bid": 12,
},
{
"name": "jack",
"bid": 69,
},
]
highestBid = 0
highestBidData = {}
for i in bidders:
if i['bid'] > highestBid:
highestBid = i['bid']
highestBidData = i
print("Congratulations {0}! Your bid of {1} `enter code
here`wins!".format(highestBidData['name'],highestBidData['bid']))
bidders = [
{
"name": "nicholas",
"bid": 12,
},
{
"name": "jack",
"bid": 69,
},
]
maxBidder = max(bidders, key=lambda x:x['bid'])
print("Congratulations {}! Your bid of {} wins!".format(maxBidder['name'],maxBidder['bid']))
In a for loop with python is 'i' not automatically an integer?
Example : for i in dictionary: Does i not equal 0, 1, 2 so on?
No
A very easy way to find out what it is is simply:
for i in bidders:
print(i)
print(type(i))
Output:
{'name': 'nicholas', 'bid': 12}
<class 'dict'>
{'name': 'jack', 'bid': 69}
<class 'dict'>
I believe what you’re looking for is bid = i[‘bid’]. i in this case is simply part of the dictionary. So for each entry, you want the value of ’bid’.
I'm trying to give the user information about the product, but how can I give it to them in case they add another product to the order?
import datetime
db = [
{
'product': 'cola',
'price': {
'USD': '2',
'GEL': '6'
},
'amount': 20,
'validity': '17/12/2019'
},
{
'product': 'cake',
'price': {
'USD': '3',
'GEL': '9'
},
'amount': 15,
'validity': '17/12/2019'
},
{
'product': 'tea',
'price': {
'USD': '1',
'GEL': '3'
},
'amount': 14,
'validity': '17/12/2019'
},
]
amount_of_product = {}
validity_of_product = {}
prices_of_product = {}
for i in db:
amount_of_product.update({i["product"]: i["amount"]})
validity_of_product.update({i["product"]: i["validity"]})
prices_of_product.update({i["product"]: i["price"]})
adLoop = True
final_price = []
while adLoop:
user_input = input("Please enter a product name: ")
if user_input in amount_of_product.keys() and validity_of_product.keys():
print(f"Currently, we have {amount_of_product[user_input]} amount of {user_input} left, "
f"which are valid through {validity_of_product[user_input]}")
user_input_two = int(input("Please enter the amount: "))
user_input_three = input("In which currency would you like to pay in?(GEL or USD: ").upper()
price = prices_of_product[user_input][user_input_three]
total = user_input_two * int(price)
if user_input_three == "GEL":
final_price.append(total)
print(f"Your order is: {user_input_two} {user_input} and total price for it is: {total}₾")
elif user_input_three == "USD":
final_price.append(total * 3)
print(f"Your order is: {user_input_two} {user_input} and total price for it is: {total}$")
stop_or_order = input("Would you like to add anything else?: ")
if stop_or_order == "yes":
adLoop = True
elif stop_or_order == "no":
adLoop = False
so if user orders cola and cake, I want the output to look like this:
Your order is 1 cola and 1 cake and total price of it is: sum(final_price)
But every time I execute the code, the older input gets removed and I get the newer input as a result. I want to save it somewhere and show the user everything he/she ordered.
You're defining user_input inside the loop, so it gets overwritten each iteration. You could define an dict
user_shopping_cart = {
'cola':0,
'cake':0,
'tea':0
}
before the while loop and update the cart as the user puts items inside,
then generate the output with data from the cart.