I want the user to pick an item from the shop and I want to use a loop to keep track of the prices(the value in the dictionary) to add up and keep a running total after every input from user. If the user inputs something that is not in the dictionary, it should say that it does not exist.
thanks in advance for help
def main():
machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7}
for key, value in machine.items():
print(key,value)
print("------------------------------")
selection = input("Please choose the number of the item you would like to purchase: ")
total=0
for i in machine:
if selection=="1":
print("You chose shirt and your total is: $", machine["1.shirt: $"])
elif selection=="2":
print("You chose shirt and your total is: $", machine["2.pants: $"])
elif selection=="3":
print("You chose shirt and your total is: $", machine["3.sweater: $"])
elif selection=="4":
print("You chose shirt and your total is: $", machine["4.socks: $"])
elif selection=="5":
print("You chose shirt and your total is: $", machine["5.hat: $"])
else:
print("Your option does not exist. Your total is: ",total)
You should update the value of total every time a choice is made. See example below
def main():
machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7}
total=0
for key, value in machine.items():
print(key,value)
print("------------------------------")
while True: # Keep Looping
selection = input("Please choose the number of the item you would like to purchase: ")
if selection=="1":
total += machine["1.shirt: $"];
print("You chose shirt and your total is: $", total)
elif selection=="2":
total += machine["2.pants: $"];
print("You chose shirt and your total is: $", total)
else:
print("Your option does not exist. Your total is: ",total)
break
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
So, for my school project, that's due tomorrow, I was tasked with making a simple game from if statements. That is exactly what I tried doing, but whenever I run the game and try buying something else other than tomatoes, I still end up buying tomatoes. I don't know what I did wrong, so I am hoping someone can help me.
I'm really new to coding so I'm sorry if this is an annoying question or anything like that.
Here is the code:
money = 50 #Money that is in the players pocket
print("Welcome to our Shop!")
print("You have " + str(money) + " dollars in your wallet.") #starting balance
if input("Would you like to enter? Y/N ") == 'Y' or 'y': #go into the shop
print("You entered the shop.")
if input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ") == 'tomatoes' or 'Tomatoes' or 'tomato' or 'Tomato' or 't' or 'T': #choose to buy tomatoes
sum = int(money) - 5
print("You bought tomatoes. You have " + str(sum) + " dollars left.") #end balance if you choose tomatoes
elif input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ") == 'potatoes' or 'Potatoes' or 'potato' or 'Potato' or 'p' or 'P': #choose to buy potatoes
sum = int(money) - 7
print("You bought potatoes. You have " + str(sum) + " dollars left.") #end balance if you choose potatoes
elif input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ") == 'cucumbers' or 'Cucumbers' or 'cucumber' or 'Cucumber' or 'c' or 'C': #choose to buy cucumbers
sum = int(money) - 10
print("You bought cucumbers. You have " + str(sum) + " dollars left.") #end balance if you choose cucumbers
if input("Would you like to enter? Y/N ") != 'Y' or 'y': #don't go into the shop
print("You turned around and walked away from the shop.\n")
Thanks. Hope you can help me.
As already said, there are multiple issues with your code.
First, as already mentioned, input() == 'Y' or 'y' does not work. You need to use input().lower() == 'y', or input() in ['y','Y']. You should definately use this list method in your later checks, as it shortens your if clauses a lot.
Second, using buit in function names as a variable name is never a good idea, because you can't use the function later on.
Third, mind your indentation. You don't need to indent code more for every if statement, you can just indent it the same.
Fourth, you should not convert your money variable to int every time, as it is already int.
Fifth, you should save the result of your inputs into variables. Now, if the user types in patatoes in the first input, then there will be asked him another time what he wants to buy instead of the user being noticed that he just buyed patatoes.
I would suggest the following:
money = 50 #Money that is in the players pocket
print("Welcome to our Shop!")
print("You have " + str(money) + " dollars in your wallet.") #starting balance
yn=input("Would you like to enter? Y/N ")
if yn.lower() == 'y': #go into the shop
print("You entered the shop.")
tobuy=input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ")
if tobuy.lower() in ["tomatoes","tomato","t"]: #choose to buy tomatoes
balance = money - 5
print("You bought tomatoes. You have " + str(balance) + " dollars left.") #end balance if you choose tomatoes
elif tobuy.lower() in ["patatoes","patato","p"]: #choose to buy potatoes
balance = money - 7
print("You bought potatoes. You have " + str(balance) + " dollars left.") #end balance if you choose potatoes
elif tobuy.lower()in ["cumcumbers","cumcumber","c"]: #choose to buy cucumbers
balance = money - 10
print("You bought cucumbers. You have " + str(balance) + " dollars left.") #end balance if you choose cucumbers
else: #don't go into the shop
print("You turned around and walked away from the shop.\n")
In the following example, the user is asked what he wants to buy every time again, such that he can buy multiple things. Do also notice that you should change the original money variable instead of creating a new one, such that his money decreases every time he buys something.
money = 50 #Money that is in the players pocket
print("Welcome to our Shop!")
print("You have " + str(money) + " dollars in your wallet.") #starting balance
yn=input("Would you like to enter? Y/N ")
if yn.lower() == 'y': #go into the shop
print("You entered the shop.")
print("You are at the vegetables isle.")
if input("Do you want to buy tomatoes($7)?").lower()=='y': #choose to buy tomatoes
money = money - 5
print("You bought tomatoes. You have " + str(money) + " dollars left.") #end balance if you choose tomatoes
if input("Do you want to buy potatoes ($7)").lower() == 'y': #choose to buy potatoes
money = money - 7
print("You bought potatoes. You have " + str(money) + " dollars left.") #end balance if you choose potatoes
if input("Do you want to buy cucumbers? ($10) ").lower() == 'y': #choose to buy cucumbers
money = money - 10
print("You bought cucumbers. You have " + str(money) + " dollars left.") #end balance if you choose cucumbers
else: #don't go into the shop
print("You turned around and walked away from the shop.\n")
from dataclasses import dataclass
from typing import List
#dataclass
class Product:
name: str
plural: str
price: int
key: chr
def __str__(self):
return f'{self.plural}, (${self.price})'
#dataclass
class Customer:
money: int
products: List[Product]
def buy(self, p: Product):
self.money -= p.price
self.products.append(p)
print(f'You bought {p.name}. You have {self.money} dollars left.')
def enter(self, s):
print("You entered the shop.")
s.vegetables_isle(self)
#dataclass
class Shop:
products: List[Product]
def vegetables_isle(self, c: Customer):
print("You are at the vegetables isle.")
print("Do you want to buy", end=' ')
for p in self.products[:-1]: print(p, end = ' ')
print(f'or {self.products[-1]}')
answer = input('choice: ')
for p in self.products:
if answer.lower() in [p.name, p.plural, p.key]:
return c.buy(p)
if __name__ == '__main__':
shop = Shop(products = [
Product(name='tomato', plural='tomatoes', price=5, key='t'),
Product(name='potato', plural='potatoes', price=7, key='p'),
Product(name='cucumber', plural='cucumbers', price=10, key='c'),
])
customer = Customer(50, products=[])
choice = input("Would you like to enter? Y/N ")
if choice.lower() == 'y':
customer.enter(shop)
else:
print("You turned around and walked away from the shop.\n")
I'm trying to create a menu for a POS like system. I have my gift card balances with their numbers and I'm trying to incorporate this in a menu. In the menu for example, if a user click the number '1', I want the menu to prompt the user for the gift card number in which they will need to enter the correct gift card number (giftnum1). If the user does not click on a valid number or does not enter the correct gift card, I would like the menu to ask the user to click on a valid number or if the user enters the wrong gift card number, I would like for the menu to ask the user to check the gift card number and try again. I am new at this, so I know that most of my menu code is wrong and could be corrected somehow, but I'm not sure how to do this and all other posts relating to this do not make sense with this post.
Here is my code that I have:
gift1 = 100
gift2 = 13.50
gift3 = 67.40
giftnum1 = 123456
giftnum2 = 998765
giftnum3 = 456789
print("Here are your current gift cards with the current balances: " + "$" + str(gift1) + " with the gift \ncard number of " + str(giftnum1) + ", $" + str(gift2) + " with a gift card number of " + str(giftnum2) + ", and $" + str(gift3) + " with a gift card number of " + str(giftnum3) + ".")
#making the POS system
def itemmenu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
print ("1. Nike Shoes ($100)")
print ("2. Bluetooth Headphones ($67.40)")
print ("3. Gloves ($13.50)")
print ("4. Exit")
loop = True
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
input("Please enter the correct gift card to buy the Nike Shoes: ")
if buyitems == giftnum1:
print("You have successfully entered the correct gift card to buy the Nike Shoes, please follow the directions to be sent a confirmation email.")
if buyitems != giftnum1:
print("You have entered an incorrect gift card number.")
elif buyitems == 2:
input("Please enter the correct gift card to but the Bluetooth Headphones: ")
if buyitems == giftnum2:
print("You have successfully entered the correct gift card to buy the Bluetooth Headphones, please follow the directions to be sent a confirmation email.")
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
input("Please enter the correct gift card to buy the Nike Shoes: ")
if buyitems == giftnum1:
You aren't saving the result of the second input() call, so buyitems is still the same value it was before.
You probably want something like this:
if buyitems == 1:
giftcard = int(input("Please enter the correct gift card to buy the Nike Shoes: "))
if giftcard == giftnum1:
Please try below code :
gift1 = 100
gift2 = 13.50
gift3 = 67.40
giftnum1 = 123456
giftnum2 = 998765
giftnum3 = 456789
print("Here are your current gift cards with the current balances: " + "$" + str(gift1) + " with the gift \ncard number of " + str(giftnum1) + ", $" + str(gift2) + " with a gift card number of " + str(giftnum2) + ", and $" + str(gift3) + " with a gift card number of " + str(giftnum3) + ".")
#making the POS system
def itemmenu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
print ("1. Nike Shoes ($100)")
print ("2. Bluetooth Headphones ($67.40)")
print ("3. Gloves ($13.50)")
print ("4. Exit")
loop = True
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
while loop:
giftcardno = int(input("Please enter the correct gift card to buy the Nike Shoes: "))
if giftcardno == giftnum1:
print("You have successfully entered the correct gift card to buy the Nike Shoes, please follow the directions to be sent a confirmation email.")
break
else:
print("You have entered an incorrect gift card number. Try again")
elif buyitems == 2:
giftcardno = input("Please enter the correct gift card to but the Bluetooth Headphones: ")
if giftcardno == giftnum2:
print("You have successfully entered the correct gift card to buy the Bluetooth Headphones, please follow the directions to be sent a confirmation email.")
else:
print("You have entered an incorrect gift card number. Try ag")
else:
break
Hetal Thaker and John Gordon answers are what you are looking for. One issue that may arise though, as you have probably noticed, is that your loop becomes endless even when you select the correct gift card number. To fix that simply set your loop variable to False once an item is purchased and it will work.
I have played around with your code a bit and made some transformations using dictionaries and less hard coding. Check it out, it might help in case you have larger data of variables - you can simply put them into the 2 dictionaries and the rest will work on it's own. Note that I did not implement any logic on what happens when the user selects "Exit" as I am not sure what behavior exactly you expect from the program for that. It would also be good to add logic in case the correct gift card is entered but its balance is not enough.
gift1_balance = 100
gift2_balance = 13.50
gift3_balance = 67.40
gift1_num = 123456
gift2_num = 998765
gift3_num = 456789
gift_cards = {gift1_num: gift1_balance, gift2_num: gift2_balance, gift3_num: gift3_balance}
merch_to_sell = {"Nike Shoes": [100, 1], "Bluetooth Headphones": [67.40, 2], "Gloves": [13.50, 3]}
print("Here are your current gift cards with the current balances:")
for key, value in gift_cards.items():
print(f"${value} with the gift card number of {key}")
def item_menu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
index = 1
for key, value in merch_to_sell.items():
print(f"{index}. {key} (${value[0]:.2f})")
index += 1
print(f"{index}. Exit")
is_item_bought = False
while not is_item_bought:
item_menu()
number_of_item = int(input("Enter the number corresponding to the item that you would like to buy: "))
current_item = 0
current_price = 0
current_index = 0
get_gift_num = 0
for k, v in merch_to_sell.items():
current_item = k
current_price = v[0]
current_index = v[1]
if is_item_bought:
break
if number_of_item == current_index:
get_gift_num = int(input(f"Please enter the correct gift card to buy the {current_item}: "))
for k, v in gift_cards.items():
if get_gift_num == k and gift_cards[k] == current_price:
print(f"You have successfully entered the correct gift card to buy the {current_item}, please follow the directions to be sent a confirmation email.")
is_item_bought = True
break
if not is_item_bought:
print("You have entered an incorrect gift card number.")
If you take this code, you can refactor it and eliminate some unnecessary variables within it and optimize it even further.
Cheers!
I am new to Python. I created a program that calculates shipping and total cost. I have it loop the user input based on user selecting y or n. I am struggling figuring out how to display a message if the user enters a negative number. I tried the if statement but the console error message displays. I want it to just display the error message I supplied. I believe I need to add a try statement?
print ("Shipping Calculator")
answer = "y"
while answer == "y":
cost = float(input("Cost of item ordered: "))
if cost <0:
print ("You must enter a positive number. Please try again.")
elif cost < 30:
shipping = 5.95
elif cost > 30 and cost <= 49.99:
shipping = 7.95
elif cost >= 50 and cost <= 74.99:
shipping = 9.95
else:
print ("Shipping is free")
totalcost = (cost + shipping)
print ("Shipping cost: ", shipping)
print ("Total cost: ", totalcost)
answer = input("\nContinue (y/n)?: ")
else:
print ("Bye!")
Try adding a continue.
With the continue statement you are going to go to the next loop iteration directly
print ("Shipping Calculator")
answer = "y"
while answer == "y":
cost = float(input("Cost of item ordered: "))
if cost <0:
print ("You must enter a positive number. Please try again.")
continue
elif cost < 30:
shipping = 5.95
elif cost > 30 and cost <= 49.99:
shipping = 7.95
elif cost >= 50 and cost <= 74.99:
shipping = 9.95
else:
print ("Shipping is free")
totalcost = (cost + shipping)
print ("Shipping cost: ", shipping)
print ("Total cost: ", totalcost)
answer = input("\nContinue (y/n)?: ")
else:
print ("Bye!")
You can also control that cost should be a number and possitive with this:
print ("Shipping Calculator")
answer = "y"
while answer == "y":
cost_string = input("Cost of item ordered: ")
if not cost_string.isdigit():
print ("You must enter a positive number. Please try again.")
continue
cost = float(cost_string)
if cost < 30:
shipping = 5.95
elif cost > 30 and cost <= 49.99:
shipping = 7.95
elif cost >= 50 and cost <= 74.99:
shipping = 9.95
else:
print ("Shipping is free")
totalcost = (cost + shipping)
print ("Shipping cost: ", shipping)
print ("Total cost: ", totalcost)
answer = input("\nContinue (y/n)?: ")
else:
print ("Bye!")
I decided that I would write a code to simulate a betting game, where you guess the number the dice will land on. Eventually, the code became a full-blown simulator, with credit-card withdrawals and different dice types and stakes (don't ask me why there's a 4-sided dice, I doubt it's possible).
Anyway, I kept getting the same error. This is my code:
import random
from random import randint
diea = randint(1,4)
dieb = randint(1,5)
diec = randint(1,6)
jackpot = randint(1,30)
chance = randint (1,30)
cquit = "a"
bal = 10
credcard = 100
withdrawal = 0
deposit = 0
if jackpot == chance:
print("You won the jackpot of 10k!")
bal = bal + 10000
while cquit.lower() == "a":
print ("Your balance is $", bal)
print ("Your credit card balance is $", credcard)
choicea = input("Would you like to deposit / withdraw money - a for deposit, b for withdrawal, anything else to skip: ")
if choicea.lower() == "a":
deposit = int(input("How much would you like to deposit - you have $", bal," on you right now: "))
if deposit > bal:
print ("You do not have enough money - cancelling process")
else:
credcard = deposit + credcard
bal = bal - deposit
print ("Your balance is $", bal)
print ("Your credit card balance is", credcard)
if choicea.lower() == "b":
withdrawal = int(input("How much money would you like to withdraw - you have $", credcard," on your card"))
if withdrawal > credcard:
print ("Your card does not allow overdrafts - cancelling process")
else:
bal = withdrawal + bal
credcard = credcard - withdrawal
print ("Your balance is $", bal)
bet = int(input("How much would you like to bet?: "))
if bet > bal:
print ("You do not have enough money")
else:
diechoice = input("Choose die - A (1-4, x2), B (1-5, x3), C(1-6, x4): ")
if diechoice.lower() == "a":
guess = int(input("What will the die land on?: "))
if guess == diea:
print ("Correct guess - balance doubled")
bal = bal + bet
if guess > 4:
print ("That is above the die's capacity - bet cancelled")
if guess != diea:
print ("Incorrect guess - bet removed from balance")
bal = bal - bet
if diechoice.lower() == "b":
guess = int(input("What will the die land on?: "))
if guess == diea:
print ("Correct guess - tripling balance")
bet = bet*2
bal = bal + bet
if guess > 5:
print ("That is above the die's capacity - bet cancelled")
if guess != dieb:
print ("Incorrect guess - bet removed from balance")
bal = bal - bet
if diechoice.lower() == "c":
guess = int(input("What will the die land on?: "))
if guess == diea:
print ("Correct guess - quadrupling balance")
bet = bet*3
bal = bal + bet
if guess > 6:
print ("That is above the die's capacity - cancelling bet")
if guess != diec:
print ("Incorrect guess - bet removed from balance")
bal = bal - bet
elif diechoice.lower() != "a" and diechoice.lower() != "b" and diechoice.lower() != "c":
print ("Incorrect input - skipping bet")
cquit = input("a to continue, anything else to end: ")
if cquit.lower() == "a":
if bal == 0 and credcard == 0:
print ("ending program - you are bankrupt")
cquit = "b"
if bal > 0:
print ("continuing program")
print ("...")
print ("...")
print ("...")
else:
print ("ending program")
This is the error I get in the code when testing it. It happens when I enter a or b on the first input statement whenever it loops:
Traceback (most recent call last):
File "D:\FAKE NEWS\du.py", line 30, in <module>
withdrawal = int(input("How much money would you like to withdraw - you have $", credcard," on your card"))
TypeError: input expected at most 1 arguments, got 3
I've been reading other reports on the same errors but I'm too bad at Python to understand any of it.
input() is not like print(), you can't give it multiple arguments and expect it to concatenate them automatically in the prompt.
You have to do the string formatting yourself.
withdrawal = int(input("How much money would you like to withdraw - you have $%.2f on your card" % (credcard)))
deposit = int(input("How much would you like to deposit - you have $" + str(bal) + " on you right now: "))
and
withdrawal = int(input("How much money would you like to withdraw - you have $"+ str(credcard) + " on your card"))
You're passing three arguments to input, but it only takes one.
To put a number into a string, use str.format:
prompt = "You have ${} on your card.".format(dollars)
input(prompt)
This inserts the value of dollars as the first "replacement field" ({}), formatting it by calling str. You can add multiple replacement fields, and you can name them like so:
"x is {}, y is {}".format(x, y)
"x is {1}, y is {0}".format(y, x) # note switched arguments
"x is {x} y is {y}".format(x=x, y=y)
If you are using Python 3.6 or later, you can use an f-string instead:
current_balance = 100;
f"You have ${current_balance} on your card."
There are many other things you can do with the string-formatting syntax. This answer provides a quick look at a few of them, if you don't want to read the documentation.
change input line from
deposit = int(input("How much would you like to deposit - you have $", bal," on you right now: "))
to
deposit = int(input("How much would you like to deposit - you have $"+str(bal)+" on you right now: "))
I'm making a little application in python, but i have no idea what to do next.
#!/usr/bin/env python
print("Welcome to the store!")
price_list = [['apple', 'orange', 'grapefruit', 'bomb', 'gun'], [3, 2, 5, 15, 10]]
inventory = []
print("You can buy the following things")
print(price_list[0][0])
print(price_list[1][0], 'dollars')
print(price_list[0][1])
print(price_list[1][1], 'dollars')
print(price_list[0][2])
print(price_list[1][2], 'dollars')
print(price_list[0][3])
print(price_list[1][3], 'dollars')
print(price_list[0][4])
print(price_list[1][4], 'dollars')
budget = 20
buy = input("What would you like to buy? Type in one of the previous options to buy something You only have 20 dollars to spend though! ")
print("You bought", buy)
if budget >= 0:
if buy == 'apple':
print("It cost 3 dollars")
budget -= 3
inventory.append('apple')
print("Your inventory is below")
print(inventory)
if buy == 'orange':
print("It cost 2 dollars")
budget -= 2
inventory.append('orange')
print("Your inventory is below")
print(inventory)
if buy == 'grapefruit':
print("It cost 5 dollars")
budget -= 5
inventory.append('grapefruit')
print("Your inventory is below")
print(inventory)
if buy == 'bomb':
print("It cost 15 dollars")
budget -= 15
inventory.append('bomb')
print("Your inventory is below")
print(inventory)
if buy == 'gun':
print("It cost 10 dollars")
budget -= 10
inventory.append('gun')
print("Your inventory is below")
print(inventory)
I want to make it so i can add one thing, then be able to add another thing until i have reahed my budget, but if i use a while statement, it just keeps adding the thing i buy! help please!
Changing if budget >= 0 to while budget >= 0 is the right idea, you just have to move the request for user input into the while loop as well. That way it will ask for input, check it against the items in the shop, then if budget >= 0 it will do it again, starting with requesting more input.
#!/usr/bin/env python
print("Welcome to the store!")
setup_price_list() #pseudocode
budget = 20
while budget >= 0:
buy = input("What would you like to buy?")
if buy == 'apple':
print("It cost 3 dollars")
budget -= 3
inventory.append('apple')
print("Your inventory is below")
print(inventory)
#the rest of the if statements
print("You bought", buy)
print("Your inventory is below")
print(inventory)
Once you have got that working, I suggest you take a look at the Python Data Structure called a dictionary. It can make code like this much simpler, for example:
print("Welcome to the store!")
price_list = {'apple':3, 'orange':2, 'grapefruit':5, 'bomb':15, 'gun':10}
print("You can buy:")
for key in price_list:
item = key
price = price_list[key]
print(item, price)
budget = 20
while budget > 0:
buy = raw_input("What do you want to buy?")
price = price_list[buy] #You will get an error if you give it a key it doesn't have
budget -= price
print("You bought: ", buy)
print("It costed: $", price)
Oh and you may want to add in a check to see whether you actually have enough money left to buy the item before you buy it, else you can still buy anything as long as you aren't in debt, I'll leave that to you to figure out :)