Ask coding questions

← Back to all posts
HELP
AdvaitoWan (1)

So, i'm making a Text Adventure Game but I need help. I am trying to make a system where I have a set amount of money, and when I type in an item and say confirm, I have the Item and My balance goes down by the price of the item.

Comments
hotnewtop
OldWizard209 (1498)

You can do this simply by using plain if statements.

Here are the steps

  • Set an amount of money.
  • Create a list of items.
  • Take user input.
  • If user input is in the items' list, then
  • Compare user input with list items and the one that matches, subtract the money from it.

Here is the code:

items = ['bottle', 'cup', 'glass', 'plate']
money = 100

user_input = input("What item do you want to buy?: ")

if user_input == 'bottle' and money != 0:
    money -= 15
    print(money)
    break
elif user_input == 'cup' and money != 0:
    money -= 10
    print(money)
    break
elif user_input == 'glass':
    money -= 20
    print(money)
    break
elif user_input == 'plate' and money != 0:
    money -= 25
    print(money)
    break
else: print("You broke LOL")

But, while coding, always use efficient code. The above code is repetitive so I would recommend using a dictionary. Set key, value pairs of prices, and then if user input matches one of them, subtract the money:

items = {
    'bottle' : 15, # item with price
    'cup' : 10, 
    'glass' : 20, 
    'plate' : 25}

money = 100 
while True:
    user_input = input("What item do you want to buy?: ")

    if user_input not in items:
        print("What are you buying lOl.")

    if money == 0:
        print("You broke lol")
    
    money_sub = items[user_input]
    money -= money_sub
    print(money)

Hope this helps :P.

PS: Mark this answer as correct if it was helpful and cleared your problem.
AdvaitoWan (1)

@OldWizard209 There's a syntax error in both of them...