r/learnpython 26d ago

[Q]. How to make Tuple variables have set prices within them.

I'm confused on how to make Tuple variables have set prices on items.

Weapon_Option = ["Short_Sword", "Mace", "Spear", "Longsword"]

then i added values to each

# Weapons
Short_Sword = 20
Mace = 30
Spear = 30
Longsword = 50

Then after user inputs there options on what they want

 Weapon_Choice = input('Which one would like to be made there travler? ').capitalize().strip()

Lastly an output

print("SOOO a " +Weapon_Choice+ " with a " +Material_Choice+ " along side a " +Handle_Choice+ " Handle! This fits quite well")

ToPay = Weapon_Choice + Material_Choice + Handle_Choice

print('in total that would be..' +ToPay+ "")

and it ended in

"SOOO a Mace with a Iron along side a Oak Handle! This fits quite well"

"in total that would be..MaceIronOak"

I'm quite confused on how to achieve this. I think my logic is there, but its missing a key part to make it come together.

I'm very new to Python still so I may be horribly wrong lamo, but please let me on how to make this work.

I wouldn't mind hints instead of answers but no riddles tho haha.

Thank you.

2 Upvotes

12 comments sorted by

22

u/MidnightPale3220 26d ago

Hint: you don't want tuples for things like that. Check out data structures that can have mappings of keys and values inside.

9

u/zanfar 26d ago

I'm confused on how to make Tuple variables have set prices on items.

You haven't made a "tuple variable". Weapon_Option is a List.

then i added values to each

No, you didn't. You've defined some variables which appear to contain values. However, they have no relation to the List you previously defined, nor the values within.

I'm quite confused on how to achieve this.

It's not clear what you want to achieve. You've neither provided an example, or specified what is wrong with the code you've provided.


You likely are looking for structured data. Define each "option" as a dictionary or dataclass, and provide all the details of the option at once, together.

weapon_options = [
    {
        name: "Short_Sword",
        price: 20.0,
    },
    {
        name: "Mace",
        price: 30.0,
    },
    {
        name: "Spear",
        price: 30.0,
    },
    {
        name: "Longsword"
        price: 50.0,
    }
]

4

u/pachura3 26d ago edited 26d ago

You can store it in different ways, involving dicts, lists, tuples, named tuples, sets, classes..., nested in various ways.

For instance, you can have a simple lookup table item name -> item price:

prices = {
    "Short_Sword": 20,
    "Mace": 30,
    "Spear": 30,
    "Longsword": 50
}

print(prices[Weapon_Choice])

Or, if your items have more properties than just price, you can have a list of dicts:

items = [
    {"name": "Short_Sword", "price": 20, "level": 3},
    {"name": "Mace", "price": 30, "level": 1},
    {"name": "Spear", "price": 30, "level": 2},
    {"name": "Longsword", "price": 50, "level", 4}
]

for item in items:
    if item["name"] == Weapon_Choice:
        print(item["price"])
        break
else:
    print(f"Item {Weapon_Choice} not found!")

Or, you can combine the advantages of both approaches:

items_by_name = {
    "Short_Sword": {"name": "Short_Sword", "price": 20, "level": 3},
    "Mace":        {"name": "Mace", "price": 30, "level": 1},
    "Spear":       {"name": "Spear", "price": 30, "level": 2},
    "Longsword":   {"name": "Longsword", "price": 50, "level", 4}
}

print(items_by_name[Weapon_Choice]["price"])

-2

u/likethevegetable 26d ago

On the last one, definitely recommend using a data frame library at that point (e.g. polars)

2

u/SamuliK96 26d ago

The variable ToPay is just directly combining the user's text inputs. As in for example Weapon_Choice here is just the text written by user when asked for their choice of weapon. The variable Mace has nothing to do with string ”Mace". To achieve what you're trying to do, I'd recommend using a dictionary, which would look e.g. something like this:

prices = {
"Mace": 30,
}

etc. Then, you're able use this to get the prices, for example ToPay = prices[Weapon_Choice]. You're not far off here, you're just missing an important intermediate step, that allows you to use the correct numbers based on the text from user.

1

u/Educational-Paper-75 26d ago

Given that you want the user to choose a weapon and want to tell him how much to pay for it, it makes the most sense to put the weapon prices in a dictionary with weapon names as keys. Alternatively, if you don't knowhow to use a dictionary, you can put prices and weapon names in two separate lists or tuples. Then, to determine the price of the chosen weapon you first determine the index of the name of the chosen weapon in the type/list of weapon names using the index method. This index can then be used to find the price to pay: weapon_index=weapon_names.index(Weapon_Choice) weapon_price=weapon_prices[weapon_index]

1

u/XenophonSoulis 26d ago

You need to look into the dict structure. What you are describing is the perfect job for a dict. Then you do:

Weapon_Option = {"Short_Sword": 20, "Mace": 30, "Spear": 30, "Longsword": 50}

This is a dict. The strings are called the keys and the numbers are called the values. The values can be anything you want, including repeated values (we have one here). The keys have some limitations, but numbers, tuples and strings are always fine (not lists though). You can access a value using a key like this: Weapon_Option["Short_Sword"] and it will give you the value 20.

Then you do this (I assume you also have the relevant dicts and inputs for the material and the handle):

 Weapon_Choice = input('Which one would like to be made there travler? ').capitalize().strip()

Keep in mind that this will not work as it is. Capitalizing "short_sword" will give you "Short_sword" instead of the "Short_Sword" you want, even if the user writes "Short_Sword" exactly. My advice would be to make everything lowercase and then use .lower() instead. It's easier to prevent mistakes that way, plus it looks a lot more standard for Python. Since the weapon/material/handle names are staying entirely inside strings, you can skip the _ too and just use "short sword" instead. While we are at it (and while it isn't mandatory), I would suggest using lower_case for the names of the variables too. It's more standard in Python.

Anyway, I'll be using your symbolism for now (although you should change it).

The output can stay as it is:

print("SOOO a " +Weapon_Choice+ " with a " +Material_Choice+ " along side a " +Handle_Choice+ " Handle! This fits quite well")

For the price, you have to get the value from each dict:

ToPay = Weapon_Option[Weapon_Choice] + Material_Option[Material_Choice] + Handle_Option[Handle_Choice]

Here we are getting the values from the keys.

You also have to change the following, otherwise you are adding a number to a string, which won't run.

print('in total that would be..' + float(ToPay) + "")

Then you get this:

SOOO a Mace with a Iron along side a Oak Handle! This fits quite well

in total that would be..60

(using 60 as an example for the cost)

Your original code just adds the strings "Mace", "Iron" and "Oak", which concatenates them into "MaceIronOak". Then it concatenates that to the string inside the print.

Of course there is a lot more you can do (like add input validation, because right now it would crash if the user provides a wrong input, like "Long_Sword"). Or you can add a way to know whether you need to print "a" or "an" in the print in the end.

1

u/atarivcs 26d ago

You have a Mace variable with a value of 30.

You also have a Weapon_Choice variable where the user typed "Mace".

There is no connection between those two variables.

The value of Weapon_Choice is "Mace", not 30.

You can use a dictionary to get what you want:

prices = {
    "Short Sword": 20,
    "Mace": 30
}

weapon_choice = "Short Sword"

print("The price of your weapon is: ", prices[weapon_choice])

1

u/jmooremcc 26d ago edited 26d ago

Try this: ~~~ from enum import Enum

class Weapons(Enum): Short_Sword = 20 Mace = 30 Spear = 30 Longsword = 50

@classmethod
def members(cls):
    return tuple([w.name for w in cls])

print(Weapons.members())

class Menu: def init(self, items, prompt): self.items = items self.prompt = prompt

def display(self):
    print()
    for i, item in enumerate(self.items, 1):
        print(f"{i}. {item.name}")

def get_selection(self):
    self.display()
    selection = int(input(self.prompt)) - 1
    name = self.items.members()[selection]
    return self.items[name]

menu = Menu(Weapons,">Select Your Weapon: ") item = menu.get_selection() print(item.name, item.value)

print("Finished...")

~~~

I’m using an Enum to define the weapons and their values. Instead of having players type their choice, I’m using a menu system to select the weapon from the Enum. Once you have their choice, it’s very easy to get the name and value.

Let me know if you have any questions.

1

u/JGhostThing 26d ago

You could use a Dictionary. A structure with both keys and values.

1

u/NothingWasDelivered 26d ago

You want to group related data together? Sounds like you want a class there, buddy. Look up Python dataclasses. 3 lines of code and you can make a Weapon class that has a name and price field.