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).
Related
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/
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
This code is intended to display the inventory when inventory_check is called, then enable the player to select any item from the list by using the item_mod variable to display the name, type, and examine dialogue from the corresponding dictionary item.
# WEAPONS AND GEAR #
dicts={"bronze sword": {
"name": "Bronze Sword",
"type": "weapon",
"atk": "3",
"examine": "A shiny bronze sword.",
},
"turian garb": {
"name": "Turian Garb",
"type": "Armour",
"def": "1",
"examine": "Your combat uniform.",
},
"rusty buckler": {
"name": "Rusty Buckler",
"type": "Shield",
"def": '1',
"examine": "An old buckler, standard."
},
"test item": {
"name": "test",
"type": "weapon",
"atk": '1',
"examine": "Hope this works (:"
}
}
######################
def inventory_check():
os.system('clear')
print(inventory)
time.sleep(1)
mid_print("How would you like to interact with the inventory? Type the item and then what to do with it. \n")
mid_print("You can also type exit to leave the inventory. \n")
print(inventory)
item_mod = input(Green + "Which item to interact with? > \n" + reset)
if item_mod in inventory:
print (item_mod["name"])
print (item_mod["type"])
print (item_mod["examine"])
elif item_mod in ['leave', 'exit', 'e']:
location_check()
else:
mid_print("That is not an item in your inventory. remember to punctuate correctly. \n")
inventory_check()
However, it refuses to run the code, claiming "string indices must be integers". I haven't used integers, so am not sure where i have gone wrong. Thank you.
I guess you want to do
if item_mod in inventory:
print (inventory[item_mod]["name"])
print (inventory[item_mod]["type"])
print (inventory[item_mod]["examine"])
instead?
I'm trying to make a length check on my dictionary as a form of simple validation. For example I'm trying to put a limit of number of players that can join a specific team which is a nested dictionary. Here's what I've done so far
teamS = {
"Team 1": {"Team Ahab":["Venom,Paz,Chico,Kaz,Miguel"],"Score":[],"Event":[]},
"Team 2": {"Team Ishmael":[],"Score":[],"Event":[]},
"Team 3": {"Team Miller":[],"Score":[],"Event":[]},
"Team 4": {"Team Raiden":[],"Score":[],"Event":[]}}
if len(teamS["Team 1"]["Team Ahab"]) > 5:
teamS["Team 1"]["Team Ahab"].pop(5)
print("This team is full so please join another one instead")
My ideal output would be like this
teamchoice = input("What team do you want to join) ("Team Ahab")
print("This team is full so please join another one)
This is poor design. You have two keys that make it harder for you to work. If you want to key by team name, that's fine, but don't make a redundant team ID. Just use a dictionary where the team is the key and the roster is a list of names, with built-in len.
teams = {
"Ahab": {
"roster": ["Venom", "Paz", "Chico", "Kaz", "Miguel"],
"Score": [],
"Event": []
},
"Ishmael" : {
"roster:[],
"Score": [],
"Event": []
},
...
}
Simply look up the given team; let's just call that pref_team.
if len(teamS[pref_team][roster]) >= 5:
# reject membership
That should be enough to get you moving.
Based on your code, to get the len of the team, you should do something like this:
print(len(str(teamS["Team 1"]["Team Ahab"]).split(",")))
You need to get the Dictionary inside the Team number, and then, the list of members is just an string separated by commas
Given the following data:
diccionario_datos_clientes = [
{"Name": "Marcos", "Age": 23, "Ranking": 14, "Contact":{ "Work": 99000001, "Personal": 7222003}},
{"Name": "Hugo", "Age": 26, "Ranking": 83, "Contact": { "Work": 99000002, "Personal": 97220042}},
{"Name": "Manuel", "Age": 13, "Ranking": 2, "Contact": { "Work": 99000003, "Personal": 47220003}},
{"Name": "Maria", "Age": 66, "Ranking": 7, "Contact": { "Work": 99000004, "Personal": 47220004}},
{"Name": "Itziar", "Age": 20, "Ranking": 23, "Contact": { "Work": 99000005, "Personal": 47220005}}
]
I have to see if the personal contact is valid. The conditions are the following:
The number has to have 8 digits min
The first number has to be 4
The numbers in the positions 4,5,6 have to be 0.
If the number is not valid I should append the name and work contact to a list.
I was able to do the first 2 conditions but i´m having trouble with the third one.
dic_llamar=[]
for dic in diccionario_datos_clientes:
if len(str(dic['Contact']['Personal']))<8:
dic_llamar.append((dic['Name'],dic['Contact']['Work']))
elif int(str(dic['Contact']['Personal'])[0])!=4:
dic_llamar.append((dic['Name'],dic['Contact']['Work']))
Ask right away if something is not clear!
I think is better to extract this into its own function
def isValid(number):
"""take a number and said if is a valid contact number"""
s = str(number)
return len(s)>=8 and s[0]=="4" and s[4:7]=="000"
(I don't understand why the other repeat the same so many times)
By putting it into its own function is more easy to check if it work (because it can be tested individually) and can be more easily use in other parts of your project if needed.
And use it like
for dic in diccionario_datos_clientes:
if isValid(dic['Contact']['Personal']):
#do something
else:
#do something else
and is cleaner and more beautiful
The last condiction is
if str(dic['Contact']['Personal'])[4:7] == '000':
On a side note, it'll be better if you used only one if:
condiction1 = len(str(dic['Contact']['Personal'])) == 8
condiction2 = str(dic['Contact']['Personal'])[0] == '4'
condiction3 = str(dic['Contact']['Personal'])[4:7] == '000'
if not (condiction1 or condiction2 or condiction3):
append(...)
I believe this would help you solve the issue, I am stating all three conditions needed to be met in the if:
for dic in diccionario_datos_clientes:
s = str(dic['Contact']['Persona'])
if (len(s) >=8) & (s[0]=='4') & (s[4:7] == '000'):
print("Valid contact!")
else:
print("Not valid contact!")
dic_llamar.append((dic['Name'],dic['Contact']['Work']))
So if all conditions are met, you will get valid contact, otherwise not valid contact. Of course you can modify this to fit your best needs.
I need to parse a nested JSON file with python and return the human-readable information back to the user.
I have tried applying a map() function alomg with dictionary that provides interpretation, but it seems to be not working with nested JSONs (or I am doing it wrong). The problem is also that the keys at level 2 may repeat as shown below, both 'consumable' and 'coin' have '1' and '2' inside them:
My JSONs look like this:
{
"consumable": {
"1": 5,
"2": 10
},
"coin": {
"1": 2000,
"2": 5000
},
"gold": 10000
}
What I expect from my script is that when I copy the JSON, I will receive a human-readable data, so 'consumable 1: 5' becomes 'mana potion: 5 pcs', ''consumable 2: 10' becomes 'HP potion: 10 pcs', and 'coin 1: 2000' becomes 'dollar: 2000', 'coin 2: 5000' becomes 'euro: 5000' and so on.
There are also things without nesting there so they should parse just like regular JSONs.
I'm not even a programmer, and have no idea how this might be done.
Not very pretty but does what you're expecting:
import json
json_string = '{ "consumable": { "1": 5, "2": 10 }, "coin": { "1": 2000, "2": 5000 }, "gold": 10000}'
content = json.loads(json_string)
for elem in content:
if elem == 'consumable':
for index in content[elem]:
if index == '1':
print(f'mana potion: {content[elem][index]} pcs')
elif index == '2':
print(f'HP potion: {content[elem][index]} pcs')
elif elem == 'coin':
for index in content[elem]:
if index == '1':
print(f'dollar: {content[elem][index]}')
elif index == '2':
print(f'euro: {content[elem][index]}')
This prints:
mana potion: 5 pcs
HP potion: 10 pcs
dollar: 2000
euro 5000
A nicer way would be to create a mapping dictionary between json and human readable strings.