I'm really new to Python (like only a month of study) and I was testing out dictionaries, so I tried to make an 'inventory' where you can pick an item from your inventory and examine it. But I can tell that I'm not doing this in the most efficient or elegant way.
Originally I thought I could make each item its separate dictionary, kind of like this:
#define what's in your inventory using a list
inventory = ["apple", "tire"]
#create a list of items with attributes using dictionaries
apple = {
"name":"apple",
"type":"fruit",
"edible":"edible",
"color":"red",
}
tire = {
"name":"tire",
"type":"object",
"edible":"not edible",
"color":"grey"
}
#explain the program to the user
print("Choose an item to examine. Items in your inventory are:")
print(*inventory, sep = ", ")
#set the loop to true
itemsloop = True
#begin the loop
while itemsloop == True:
#ask for user input
x = input()
But then I got stuck at the part where it's time to take the input and match it to the name of a dictionary, because one is a string and one isn't. The following code is working, but feels... inelegant and unnecessary to type out (prefix)-name, (prefix)-type, (prefix)-edible for every entry. I feel like there must be a simpler way to accomplish this that I'm just not seeing because I don't think like a programmer yet. I don't know.
If you can explain any more efficient methods with simple terminology (again, huge newbie not just to Python but programming in general), I'd really appreciate it!
#define what's in your inventory using a list
inventory = ["apple", "tire"]
#create a list of items with attributes using a dictionary
items = {
"apple-name":"apple",
"apple-type":"fruit",
"apple-edible":"edible",
"apple-color":"red",
"tire-name":"tire",
"tire-type":"object",
"tire-edible":"not edible",
"tire-color":"grey"
}
#explain the program to the user
print("Choose an item to examine. Items in your inventory are:")
print(*inventory, sep = ", ")
#set the loop to true
itemsloop = True
#begin the loop
while itemsloop == True:
#ask for user input
x = input()
if x in inventory:
#if the input matches something you have, find the attributes of
#the item in the inventory and print them.
print("This is a " + items[x + "-color"] + " " +
items[x + "-name"] + ", a type of " + items[x + "-type"]
+ ". It is " + items[x + "-edible"] + ".")
elif x == "quit":
#if the player wishes to quit, end the program.
itemsloop == False
break
else:
#if the item is not recognized, let the player know.
print("You don't have that in your inventory.")
(The sample output would be something like, "This is a red apple, a type of fruit. It is edible.")