My code needs to check which product/thing a number corresponds to.
Which means if I input a number, I need to know which product it corresponds to.
As far as I know, I have no idea how to do this other than elif spamming, but that makes a huge mess with a massive wall of elifs.
I've also tried reading into python dictionaries but my small brain doesn't comprehend how to pick out the value if I only have the key.
I feel like dictionaries were made for this but I still can't figure out how it works.
Is there a way to be more efficient in finding what product == number if I only have the number and a list of objects?
Example:
if thing == 1:
print("a")
elif thing == 2:
print("b")
elif thing == 3:
print("c")
and so on
CodePudding user response:
The solution with dictionaries you are struggling with is
things = {1: "a", 2: "b", 3: "c"}
print(things[thing])
CodePudding user response:
If you just want an alphabetical letter from any number, you can make a list of the alphabet and index it at "thing" spot.
alphabet[(thing - 1) % 26]
I subtracted 1 to make it zero-indexed, and % 26 ensures that it works even if the variable "thing" is too large. Alphabet can be defined a couple ways
from string import ascii_lowercase
alphabet = list(ascii_lowercase)
or
alphabet = [chr(i) for i in range(97, 123)]
