Text Adeventure python sell system - python

Credits to https://stackoverflow.com/users/5003756/james for answering my previous post Python Text adventure Selling, check if its in list with
def sell(player_inventory):
print('Available to sell::')
for i, stuff in enumerate(player_inventory, 1):
print(i, stuff)
sold = input('what item number do you want to sell? ("q" to exit)')
if sold == 'q':
return player_inventory
try:
sold = int(sold)
except ValueError:
print('Please use the item number')
return player_inventory
if sold <= len(player_inventory):
print('successfully sold!!')
player_inventory.pop(sold - 1)
return player_inventory
So anyways, thanks to James we now have a sell function which runs perfectly fine. But the thing is, I want to make it so the way the money gets added to my
player_money
How I could add money in there? When I run the sell function, it does take the item away from my inventory, but doesn't add money to
player_money

if sold <= len(player_inventory):
print('successfully sold!!')
player_inventory.pop(sold - 1)
player_money(add + amount)
return player_inventory
you have to add a function where the items amount sold is stored and then that amount would be added to the function of the money in the players inventory.

Related

How can you multiply a value from a dictionary with a number to get a real value?

store={'Rice':450,'Beans':200,'Egg':40,'Fish':250,'Spag':250}
bill=()
total=()
print('Welcome!!!we sell:',"\n",[store])
while True:
a=input('What would you like to buy?=')
b=input('how many of each product do you want?=')
if a in store:
bill=store[a]*b
print('bill=',bill)
elif a not in store:
print('Sorry we don\'t have that')
else:
total=bill+total
print('Total=',total)
Your if/elif/else is impossible, because wether a is IN the dict, wether it isn't, there is no way you into the else so put it in the if.
I'd also added a way to stop the loop by entering stop without you won't be able to stop the program and print the final total
move b input into the if, that isn't necessary to ask for quantity if the product isn't available
added int() conversion on b
store = {'Rice': 450, 'Beans': 200, 'Egg': 40, 'Fish': 250, 'Spag': 250}
print('Welcome!!!we sell:', "\n", store)
total, bill = 0, 0
while True:
a = input('What would you like to buy? ("stop" to quit): ')
print(">" + a + "<") # For OP debug purpose only, to be removed
if a == "stop":
break
if a in store:
b = int(input('how many of each product do you want?='))
bill = store[a] * b
total += bill
print(f"Total={total} (+{bill})")
else:
print('Sorry we don\'t have that')
print('Total=', total)

Vending Machine Project - Guidance on OOP code [Python]

Quite new to programming and have got an issue with some of my python code. I feel like there would be an easier way to write it/ simplify it. I am still working through it (working on the first item before and have got my 'tea' in the virtual vending machine. However I am not sure using that many if elif statements is the cleanest way to complete the code? Also, I want the code to constantly have an input available to the user so they can order more that one drink (if they have the money). So I would like it to loop and start again without losing the coin, how would I go about that?
I know it isn't much, but its my first assignment and I am happy that I have got it this far!
class Vending_Machine:
aussie_coins = (0.05, 0.10, 0.20, 0.50, 1.00, 2.00)
items = ['Tea','Coffee', 'Coke', 'Orange Juice']
item_price = [0.50, 1.00, 1.50, 1.00]
item_code = ['1', '2', '3', '4']
def __init__(self): #define total in vending machine.
self.total = 0.00
def insert_coin(self,coin):
if float(coin) not in (self.aussie_coins):
print ('The Vending Machine accepts only: {}. ' .format(self.aussie_coins), end = '')
else:
self.total += coin
print ('Currently there is a total of {: .2f} in machine' .format(self.total))
class interface(Vending_Machine):
def menu(self):
print("##################################")
print(" Welcome to my Vending Machine ")
print("All items below are readily available")
print(Vending_Machine.item_code[0], Vending_Machine.items[0], "${: .2f}".format(Vending_Machine.item_price[0])) #
print(Vending_Machine.item_code[1], Vending_Machine.items[1], "${: .2f}".format(Vending_Machine.item_price[1]))
print(Vending_Machine.item_code[2], Vending_Machine.items[2], "${: .2f}".format(Vending_Machine.item_price[2]))
print(Vending_Machine.item_code[3], Vending_Machine.items[3], "${: .2f}".format(Vending_Machine.item_price[3]))
print("##################################")
class user_input(interface):
def choice (self):
choice = input("Please enter the item code of an item you would like to purchase: ")
if choice == Vending_Machine.item_code[0]:
print ("You have selected {} - the price is ${: .2f}. Currently you have a total of ${: .2f} in the machine." .format(Vending_Machine.items[0], Vending_Machine.item_price[0], self.total))
if self.total < Vending_Machine.item_price[0]:
coins = float(input("Insert a coin into the vending machine: "))
Vending_Machine.insert_coin(self,coins)
if self.total == Vending_Machine.item_price[0]:
self.total -= Vending_Machine.item_price[0]
print('Please take your {}. There is currently ${: .2f} left in the Machine. Thanks, have a nice day!'.format(Vending_Machine.items[0], self.total))
elif self.total > Vending_Machine.item_price[0]:
self.total -= Vending_Machine.item_price[0]
print ('Please take your {}. There is currently ${: .2f} left in the Machine. Thanks, have a nice day!'.format(Vending_Machine.items[0], self.total))
elif self.total > Vending_Machine.item_price[0]:
self.total -= Vending_Machine.item_price[0]
print('Please take your {}. Total of {: .2f} in the machine' .format(Vending_Machine.items[0],self.total))
elif self.total == Vending_Machine.item_price[0]:
self.total -= Vending_Machine.item_price[0]
print('Please take your {}. Thanks, have a nice day!'.format(Vending_Machine.items[0]))
elif choice == Vending_Machine.item_code[1]:
print ("You have selected {} - the price is ${: .2f}. Currently you have a total of ${: .2f} in the machine." .format(Vending_Machine.items[1], Vending_Machine.item_price[1], self.total))
if self.total < Vending_Machine.item_price[1]:
insert_coin(input("Insert a coin into the vending machine: "))
elif self.total > Vending_Machine.item_price[1]:
self.total -= Vending_Machine.item_price[1]
print('Please take your {}. Total of {: .2f} in the machine' .format(Vending_Machine.items[1],self.total))
elif self.total == Vending_Machine.item_price[1]:
self.total -= Vending_Machine.item_price[1]
print('Please take your {}. Thanks, have a nice day!'.format(Vending_Machine.items[1]))
elif choice == Vending_Machine.item_code[2]:
print ("You have selected {} - the price is ${: .2f}. Currently you have a total of ${: .2f} in the machine." .format(Vending_Machine.items[2], Vending_Machine.item_price[2], self.total))
if self.total < Vending_Machine.item_price[2]:
insert_coin(input("Insert a coin into the vending machine: "))
elif self.total > Vending_Machine.item_price[2]:
self.total -= Vending_Machine.item_price[2]
print('Please take your {}. Total of {: .2f} in the machine' .format(Vending_Machine.items[2],self.total))
elif self.total == Vending_Machine.item_price[2]:
self.total -= Vending_Machine.item_price[2]
print('Please take your {}. Thanks, have a nice day!'.format(Vending_Machine.items[2]))
elif choice == Vending_Machine.item_code[3]:
print ("You have selected {} - the price is ${: .2f}. Currently you have a total of ${: .2f} in the machine." .format(Vending_Machine.items[3], Vending_Machine.item_price[3], self.total))
if self.total < Vending_Machine.item_price[3]: #if not the price of tea then..
insert_coin(input("Insert a coin into the vending machine: "))
elif self.total > Vending_Machine.item_price[3]:
self.total -= Vending_Machine.item_price[3]
print('Please take your {}. Total of {: .2f} in the machine' .format(Vending_Machine.items[3],self.total))
elif self.total == Vending_Machine.item_price[3]:
self.total -= Vending_Machine.item_price[3]
print('Please take your {}. Thanks, have a nice day!'.format(Vending_Machine.items[3]))
elif choice not in item_code:
print("Sorry we do not have item number {} available. Please try again" .format(choice))
vm = Vending_Machine()
i1 = interface()
u1 = user_input()
i1.menu()
u1.choice()
This is probably better suited for the code review board, but anyways...
Really great for a first project! That being said, you've already identified the major shortcoming of your code - you shouldn't have to use all those if/elifs. I also don't think you can justify wrapping most of your code into classes, like you've done. These are my suggestions:
Define two classes, VendingMachine and Item (an instance of this
class represents a single available item in the vending machine).
Follow good naming conventions. Notice the class names start with an
uppercase letter, and are camel-case.
Define an explicit entry point for your program, such as main.
Use a loop to iterate over your vending machine items when displaying
them. You can do something similar to cull all those if-statements.
Code:
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
class VendingMachine:
def __init__(self):
self.items = [
Item("Tea", 0.50),
Item("Coffee", 1.00),
Item("Coke", 1.50),
Item("Orange Juice", 1.00)
]
self.money_inserted = 0.00
def display_items(self):
for code, item in enumerate(self.items, start=1):
print(f"[{code}] - {item.name} (${item.price:.2f})")
def insert_money(self, money):
if money <= 0.00:
raise ValueError
self.money_inserted += money
def main():
vending_machine = VendingMachine()
vending_machine.display_items()
while True:
try:
user_selection = int(input("Please enter the desired item code: "))
except ValueError:
continue
if user_selection in range(1, len(vending_machine.items)+1):
break
item = vending_machine.items[user_selection-1]
print(f"You've selected \"{item.name}\" - the price is ${item.price:.2f}")
while vending_machine.money_inserted < item.price:
print(f"You've inserted ${vending_machine.money_inserted:.2f} into the machine so far.")
while True:
try:
money_to_insert = float(input("Please enter the amount of money you'd like to insert: "))
vending_machine.insert_money(money_to_insert)
except ValueError:
continue
else:
break
print(f"Thank you! Please take your \"{item.name}\".")
print(f"The remaining change in the machine is ${vending_machine.money_inserted - item.price:.2f}.")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Output:
[1] - Tea ($0.50)
[2] - Coffee ($1.00)
[3] - Coke ($1.50)
[4] - Orange Juice ($1.00)
Please enter the desired item code: d32
Please enter the desired item code: 3
You've selected "Coke" - the price is $1.50
You've inserted $0.00 into the machine so far.
Please enter the amount of money you'd like to insert: 4ff4
Please enter the amount of money you'd like to insert: 1
You've inserted $1.00 into the machine so far.
Please enter the amount of money you'd like to insert: .10
You've inserted $1.10 into the machine so far.
Please enter the amount of money you'd like to insert: .90
Thank you! Please take your "Coke".
The remaining change in the machine is $0.50.
>>>
Good work. I've got one word to say to you: loops.
Where you've got 4 lines printing the vending machine items (at the start), you could replace it with a loop, like so:
for index in range(len(VendingMachine.items)):
print(Vending_Machine.item_code[index], Vending_Machine.items[index], "${: .2f}".format(Vending_Machine.item_price[index]))
Hopefully that gives you enough information to work out how to shrink the rest of your code too. If it needs to be elif (as in, you only want to check one of them, not all of them), use a break in the loop (see below for an example of a break).
As for your second question, you could have a loop around the insert_coin function call (in the user_input function) which keeps adding coins until the user inputs 'done'.
Here's a pretty basic example. There could be better ways to do this, but it should work.
while True:
coins = float(input("Insert a coin into the vending machine: "))
if coins == "done":
break
Vending_Machine.insert_coin(self,coins)

pop from empty list error in car app

I'm mostly new to this so apologies in advance if the answer is blindingly obvious to this. For a school assignment (and out of interest also) I'm building a sort of basic car app that uses lists to store cars (objects) as they are made then a separate list to record cars that are rented.
The rent process works perfectly fine and when I tested it it was appending a car to my rentedcars list, however when I call it (rentedcars) later in a separate function its saying that it cannot pop an empty list.
I assumed this was because the list was being modified inside a function, however when I returned the outputed modified list and assigned a variable to the function for later use it gave me the error that I was calling a variable before assigning it and giving the variable a global definition didn't resolve it.
The segment of code is below, anyone have any thoughts? It would be much appreciated. I've looked this sort of problem a couple of times on the forums here but the solutions (at least as I tried to implement them) didn't seem to fix it.
The function rental_system is called later, I've just shown the section I'm having problems with due to size, all lists for the 4 types of car are made under init self. etc and work.
def rent(self, car_list, rented_cars, amount): # Process to rent a car function
if len(car_list) < amount:
print 'Not enough cars in stock' # Make sure enough cars in stock
return
total = 0
while total < amount:
carout = car_list.pop() # Pop last item from given car list and return it
rented_cars.append(carout) # Then append to a new list of rented cars that are now unavailable
total = total + 1
print 'Make: ' + carout.getMake()
print 'Colour: ' + carout.getColour()
print 'Engine Size(Cylinders): ' + carout.getEngineSize()
print 'You have rented ' + str(amount) + ' car(s)'
return rented_cars
def rented(self, car_list, rented_cars, amount): # Process for returning cars
total = 0
while total < amount:
carin = rented_cars.pop()
car_list.append(carin)
total = total + 1
print 'You have returned' +str(amount) + 'car(s)'
return rented_cars, car_list
def rental_system(self):
rentedcars = []
rented = raw_input('Are you returning or renting a car? Type either return/rent ')
if rented.lower() == 'return': # Return system
type = raw_input('Are you returning a petrol, electric, diesel or hybrid car? ')
amount = raw_input('How many would you like to return? ')
if type == 'petrol':
self.rented(self.petrolcars, rentedcars, amount)
elif type.lower() == 'diesel':
self.rented(self.dieselcars, rentedcars, amount)
elif type.lower() == 'hybrid':
self.rented(self.hybridcars, rentedcars, amount)
elif type.lower() == 'electric':
self.rented(self.electriccars, rentedcars, amount)
else:
print 'Error, please check your spelling'
return
if rented.lower() == 'rent':
Rental process
answer = raw_input('What type of car would you like? Type: petrol/diesel/hybrid/electric ')
amount = int(raw_input('How many of that type of car?'))
if answer.lower() == 'petrol':
self.rent(self.petrolcars, rentedcars, amount)
elif answer.lower() == 'diesel':
self.rent(self.dieselcars, rentedcars, amount)
elif answer.lower() == 'hybrid':
self.rent(self.hybridcars, rentedcars, amount)
elif answer.lower() == 'electric':
self.rent(self.electriccars, rentedcars, amount)
else:
print 'Error, please check your spelling'
return
The problem is that you are passing an empty list through the rental_system method to the rented method.
You have defined rentedcars = [] in rental_system method and without modifying it you are trying to pop from it in the rented method.
Why don't you add the rented_cars as an attribute in your class design?

How do I assign a variable to a price in a while loop in order to get a subtotal?

I am working on a project but I can't seem to figure out this whole while loop thing. I am creating a little receipt program and I am able to get user input for the price of their items, however many they want to enter. But I cannot figure out how to tell the program to add all of the items they input to create a subtotal. Go easy on me, I am just a beginner. Here is the code I have so far:
import locale
locale.setlocale(locale.LC_ALL, '')
print("Welcome to Publix".center(80))
while(True):
Price = float(input("Price of item: "))
if(Price == -1):
break
print("Thank you for shopping at Publix!".center(80))
#Tax = Subtotal * 0.065
You need to initialize your subtotal to 0 before loop and add the price everytime to subtotal.
import locale
locale.setlocale(locale.LC_ALL, '')
print("Welcome to Publix".center(80))
Subtotal = 0
while(True):
Price = float(input("Price of item: "))
if(Price == -1):
break
Subtotal = Subtotal + Price
print Subtotal;
print("Thank you for shopping at Publix!".center(80))
#Tax = Subtotal * 0.065
Use a variable (subtotal) to accumulate the price values. You can add a try-except-else block to prevent wrong user input that cannot be converted to float from breaking your code. With this, your code is a little less buggy:
import locale
locale.setlocale(locale.LC_ALL, '')
print("Welcome to Publix".center(80))
subtotal = 0
while True:
try:
price = float(input("Price of item (enter -1 to stop): "))
if price == -1:
break
except ValueError:
print("The format of the price you entered is not acceptable")
else:
subtotal += price
print("Thank you for shopping at Publix!".center(80))
# tax = subtotal * 0.065
I suggest you store your prices using decimal for reasons relating to accuracy.

Creating a sales list that allows users to enter multiple items

I've been working on a project for my class in python and I feel like no matter what I do I can't get it right. We're supposed to create a program that captures 3 items and then 4 bits of information for each item. AKA: Item: x, Quantity: x, price $x, weight x pounds. Then it should print out a subtotal, shipping & handling cost, tax total, and final total. The issue I'm having is that we're not allowed to create a variable for each item and must do everything in a loop. No matter what I've tried all I can do is get everything to print out the last data entered.
Here's my code so far:
def main():
#Range of 3 so that user may enter 3 seperate items
for i in range(3):
#Grabs user input for item description and/or name
strDescription = str(input("Enter description of item: "))
#Grabs user input for price of item
fltPrice = float(input("Enter price of item: $ "))
#Grabs user input for quanitity of item
intQuantity = int(input("Enter quantity of item: "))
#Grabs user input for weight of item in pounds
fltWeight = float(input("Enter weight of item in pounds: "))
#Subtotal is equal to price times number of items purchased
fltPriceSub = fltPrice*intQuantity
#Shipping 25 cents per pound
intShipping = (.25*fltWeight)
#There is a base fee of $5 per order applied to shipping
intBaseRate = 5
#Tax is 9 cents per dollar
fltTax = 0.09*fltPriceSub
fltPriceSubTotal = fltPriceSub+fltPriceSub+fltPriceSub
intShippingTotal = intShipping+intShipping+intShipping+intBaseRate
fltTaxTotal = fltTax+fltTax+fltTax
#Order total is the subtotal+shipping+tax added together
fltOrderTotal = fltPriceSubTotal+intShippingTotal+fltTaxTotal
print("You have purchased ", strDescription, "")
print("Your subtotal is ", fltPriceSubTotal, "")
print("Shipping and handling is ", intShippingTotal, "")
print("The tax is ", fltTaxTotal, "")
print("The order total is ",fltOrderTotal, "")
main()
If anyone could steer me in the right direction I would really appreciate it.

Categories

Resources