functions and returns - python

I'm new to python and I've been assigned in writing an invoice program for a hypothetical hotel. I'm running into difficulty when trying to call on functions for their return value. I could really use the help as I'm really stumped. The implementation code is to follow along with the description of the program so a handle can be put on what exactly is the mistake.
Invoice
PCCC Palace Hotel
Eddie’s Billing Statement
Number of days in hotel: 2
Room Charges $675.00
Internet Charges $29.85
Television Charges $8.85
Total Charges $703.70
Local Taxes $24.63
Total Due $728.33
Thank you for using PCCC Palace Hotel. Hope to see you again.
Requirements:
• Include relevant information in the form of comments in your code as explained in the class.
• Use a different function to handle each of
o the room type
o The Internet Access usage
o The TV usage
• The Internet and TV usage may be denied, in that case the charges would be $0.00
• All the rates are defined as local constants inside the functions
• Each function has a menu that displays the options to select from
• Each function returns the charges incurred for that option
• The local tax rate is 3.5% and is to be defined as a local constant
The problem is:
Traceback (most recent call last):
File "C:/Python33/hotel.py", line 28, in
print("Room Charges: ", roomcost())
NameError: name 'roomcost' is not defined
Code:
def main():
input = int , 2
costofinternet = costofinternet
costoftv = costoftv
customername = input("The Customer Name Please: ")
visitdays = input("Enter the Number of Days in the Hotel: ")
room = input("Rooms Used \n1 - Single Room - One Bed \n2 - Family Room - Doulble Bed \n3 - Suite \n Enter Choice 1, 2, or 3: ")
roomcost()
internet = input("Would You like Internet: ")
if internet == 'Y':
internettype = input("Internet Access Usage \n1 - Wireless \n2 - Wired \nEnter Choices 0, 1, or 2: ")
television = input("Would You like to use the TV: ")
if television == 'Y':
tvtype = input("TV Usage \n1 - Cable \n2 - Basic Channels \nEnter Choice 0, 1, or 2: ")
print("\t\t\t\t\t\t Invoice")
print("\t\tPCCC Palace Hotel")
print(customername, "'s Billing Statement")
print("Number of Days in Hotel: ", visitdays)
print("Room Charges: ", roomcost)
print("Internet Charges: ", costofinternet)
print("Television Charges: ", costoftv)
totalcharge = print("Total Charges: ", roomcost + costofinternet + costoftv)
localtaxes = print("Local Taxes: ", ((roomcost + costofinternet + costoftv) * .035))
print("\t\tTotal Due\t\t\t", totalcharge + localtaxes)
print("\t\tThank You For Using PCCC Palace Hotel. Hope To See You Again.")
def roomcost():
cost = []
if room == '1':
cost == 225
if room == '2':
cost == 325
if room == '3':
cost == 550
return(cost)
def internet():
costofinternet = []
if internettype == '0':
costofinternet == 0
if internettype == '1':
costofinternet == 9.95
if internettype == '2':
costofinternet == 5.95
return(costofinternet)
def tv():
costoftv = []
if tvtype == '0':
costoftv == 0
if tvtype == '1':
costoftv == 9.95
if tvtype == '2':
costoftv == 2.95
return(costoftv)

roomcost is a function, so you'll need to call it using the () operator, along with your other function calls:
print("Room Charges: ", roomcost())
print("Internet Charges: ", costofinternet())
print("Television Charges: ", costoftv())

Related

Check element value of specific element in list

I'm working on an assignment covering classes. There are several requirements but my program meets nearly all of them the way it is currently.
The program is to prompt the user to enter either a car or truck into their virtual garage. From there they select a number of options depending on if it is a car or truck.
The user continues doing this until they are done adding vehicles, then they get prompted with the vehicles they entered and their info.
As it is currently, I can enter an endless amount of cars or trucks and it will print what I entered correctly. It will not allow me to enter in both cars and trucks, which is what I need it to do.
I know the issue is likely with my last loop since it references carTruck and it should probably reference the value of the element in the instances list. I am unsure how to do that though.
I realize there are probably better ways to achieve this but there are certain ways it must be done according to the assignment. Also, error handling isn't needed in this so that is why it is not included.
class Vehicle:
def __init__(self, make, model, color, fuelType,options):
self.make = make
self.model = model
self.color = color
self.fuelType = fuelType
self.options = options
def getMake(self):
self.make = input('Please enter the vehicle make: ').title()
return self.make
def getModel(self):
self.model = input('Please enter the vehicle model: ').title()
return self.model
def getColor(self):
self.color = input('Please enter the vehicle color: ')
return self.color
def getFuelType(self):
self.fuelType = input('Please enter the vehicle fuel type: ')
return self.fuelType
def getOptions(self):
optionslist = []
print('\nEnter Y or N for the following options')
radio = input('Does your vehicle have a radio: ').lower()
bluetooth = input('Does your vehicle have bluetooth: ').lower()
cruise = input('Does your vehicle have cruise control: ').lower()
window = input('Does your vehicle have power windows: ').lower()
lock = input('Does your vehicle have power locks: ').lower()
mirror = input('Does your vehicle have power mirrors: ').lower()
rstart = input('Does your vehicle have remote start: ').lower()
bcamera = input('Does your vehicle have a back up camera: ').lower()
if radio == 'y':
optionslist.append('Radio')
if bluetooth == 'y':
optionslist.append('Bluetooth')
if cruise == 'y':
optionslist.append('Cruise Control')
if window == 'y':
optionslist.append('Power Windows')
if lock == 'y':
optionslist.append('Power Locks')
if mirror == 'y':
optionslist.append('Power Mirrors')
if rstart == 'y':
optionslist.append('Remote Start')
if bcamera == 'y':
optionslist.append('Backup Camera')
self.options = optionslist
return self.options
#car child class
class Car(Vehicle):
def __init__ (self, make, model, color, fuelType,options, engineSize, numDoors):
self.engineSize = engineSize
self.numDoors = numDoors
Vehicle.__init__(self, make, model, color, fuelType,options)
def getEngineSize(self):
self.engineSize = input('Please enter your engine size in liters: ')
return self.engineSize
def getNumDoors(self):
self.numDoors = input('Please enter the number of doors: ')
return self.numDoors
#pickup child class
class Pickup(Vehicle):
def __init__ (self, make, model, color, fuelType,options, cabStyle, bedLength):
self.cabStyle = cabStyle
self.numDoors = bedLength
Vehicle.__init__(self, make, model, color, fuelType, options)
def getCabStyle(self):
self.cabStyle = input('Please enter the cab style: ')
return self.cabStyle
def getBedLength(self):
self.bedLength = input('Please enter the bed length: ')
return self.bedLength
#creates instance and loops to get info for vehicles from user
instances = []
Exit = 'n'
x = 0
while Exit == 'n':
carTruck = input('Are you entering a car or truck? ')
plateNum = input('please enter your license plate number: ')
instances.append(carTruck + plateNum)
#if statement to use correct class based on user input
if carTruck == 'car':
instances[x] = Car('','','','','','','')
instances[x].getMake()
instances[x].getModel()
instances[x].getColor()
instances[x].getFuelType()
instances[x].getEngineSize()
instances[x].getNumDoors()
instances[x].getOptions()
if not instances[x].options:
print('\nYou need to select at least one option.')
Vehicle.getOptions(instances[x])
elif carTruck == 'truck':
instances[x] = Pickup('','','','','','','')
instances[x].getMake()
instances[x].getModel()
instances[x].getColor()
instances[x].getFuelType()
instances[x].getCabStyle()
instances[x].getBedLength()
instances[x].getOptions()
if not instances[x].options:
print('\nYou need to select at least one option.')
Vehicle.getOptions(instances[x])
#allows user to stop adding vehicles
Exit = input('Are you done adding vehicles (Y/N): ').lower()
x = x + 1
#loops through instances and provides output dependent on whether it is a car or truck.
b = 0
while b < len(instances):
if carTruck == 'truck':
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].cabStyle} and a {instances[b].bedLength} ft bed that runs on {instances[b].fuelType}.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
elif carTruck == 'car':
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].numDoors} door with a {instances[b].engineSize} liter {instances[b].fuelType} engine.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
b = b + 1
Output:
Are you entering a car or truck? car
please enter your license plate number: 123456
Please enter the vehicle make: ford
Please enter the vehicle model: mustang
Please enter the vehicle color: red
Please enter the vehicle fuel type: gas
Please enter your engine size in liters: 5
Please enter the number of doors: 2
Enter Y or N for the following options
Does your vehicle have a radio: y
Does your vehicle have bluetooth: y
Does your vehicle have cruise control: y
Does your vehicle have power windows: y
Does your vehicle have power locks: y
Does your vehicle have power mirrors: y
Does your vehicle have remote start: y
Does your vehicle have a back up camera: y
Are you done adding vehicles (Y/N): n
Are you entering a car or truck? truck
please enter your license plate number: 789456
Please enter the vehicle make: chevy
Please enter the vehicle model: 1500
Please enter the vehicle color: black
Please enter the vehicle fuel type: gas
Please enter the cab style: crew cab
Please enter the bed length: 6
Enter Y or N for the following options
Does your vehicle have a radio: y
Does your vehicle have bluetooth: y
Does your vehicle have cruise control: y
Does your vehicle have power windows: y
Does your vehicle have power locks: y
Does your vehicle have power mirrors: y
Does your vehicle have remote start: y
Does your vehicle have a back up camera: y
Are you done adding vehicles (Y/N): y
Traceback (most recent call last):
File "c:\Users\chris\Desktop\School\Intro to Programming\python_work\classes.py", line 138, in <module>
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].cabStyle} and a {instances[b].bedLength} ft bed that runs on {instances[b].fuelType}.')
AttributeError: 'Car' object has no attribute 'cabStyle'
``
Before you read the answer, ask yourself where did you get the carTruck instance you are trying to print.
...
You are referring to the last entry you have added instead of referring to the current instance! So correct way will be, eg.
b = 0
while b < len(instances):
if isinstance(instances[b], Pickup): #CHANGED
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].cabStyle} and a {instances[b].bedLength} ft bed that runs on {instances[b].fuelType}.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
elif isinstance(instances[b], Car): #CHANGED
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].numDoors} door with a {instances[b].engineSize} liter {instances[b].fuelType} engine.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
b = b + 1
I want to add two suggestions...
1st - don't use while loop here use for, eg.
for moving_thing in instances:
if isinstance(moving_thing, Pickup):
...
2nd - create __str__ method for each class so you could call it without checking what type of vehicle it is. More here Dunder methods, than you could call
for moving_thing in instances:
print(moving_thing)

Holiday application on Python 2.7

I have tried solve these tasks for a homework but I got stuck:
You will need to to create four functions:
Hotel cost - This function will take the number of nights as an argument and return a total cost (You can choose the price per a night)
Plane cost - This function will take the city you are flying to as an argument and return a cost for the flight (Hint: use if/else if statements in the function to retrieve a price based on the chosen city)
Car rental - This function will take the number of days as an argument and return the total cost.
Holiday cost - This function will take three arguments, number of nights, city, and days.
Using these three arguments, you can call all three of the above functions with respective arguments and finally return a total cost for your holiday.
Print out the value of your Holiday function to see the result!
Try using your app with different combinations to show it’s compatibility
with different options
This is what I have so far:
def hotel_cost(nights):
return nights * 875
def plane_cost(city):
ticket = 0
while city != 4:
if city == '1':
ticket = 750
break
elif city == '2':
ticket = 850
break
elif city == '3':
ticket = 600
break
elif city == '4':
print 'You have selected an invalid option'
else:
print 'You have selected an invalid option'
def car_rental(days):
return days * 275
def holiday_cost(nights, city, days):
nights = hotel_cost(nights)
city = plane_cost(city)
days = car_rental(days)
return nights + city + days
hotel_cost(int(raw_input('How many nights will you be staying? ')))
plane_cost(raw_input('\n1. O.R. Tambo International\n2. Capetown International\n3. King Shaka International\nWhere you flying to? '))
car_rental(int(raw_input('How many days will you need a car for?: ')))
total = holiday_cost(nights, city, days)
print total
The error I get is the following:
Traceback (most recent call last): File "C:\Users\user\Dropbox\Mengezi Dlomo-9897\intro to programming\Task 24\holiday.py", line 37, in <module> total = holiday_cost(nights, city, days) NameError: name 'nights' is not defined
You already call the 3 other functions inside holiday_cost. You don't need to call them multiple times.
Also ive made a few other helpful changes such as while city > 3: instead of while city != 4: in plane_cost() and I added a return ticket line at the end of plane_cost()
Also the line:
elif city == '4':
print 'You have selected an invalid option'
was unnecessary as city == '4' falls into the else condition.
Here is the final code:
def hotel_cost(nights):
return nights * 875
def plane_cost(city):
ticket = 0
while city > 3:
if city == '1':
ticket = 750
break
elif city == '2':
ticket = 850
break
elif city == '3':
ticket = 600
break
else:
print 'You have selected an invalid option'
return ticket
def car_rental(days):
return days * 275
def holiday_cost(nights, city, days):
nights = hotel_cost(nights)
city = plane_cost(city)
days = car_rental(days)
return nights + city + days
nights = int(raw_input('How many nights will you be staying? '))
city = raw_input('\n1. O.R. Tambo International\n2. Capetown International\n3. King Shaka International\nWhere you flying to? ')
days = int(raw_input('How many days will you need a car for?: '))
total = holiday_cost(nights, city, days)
print total
You wrote:
total = holiday_cost(nights, city, days)
but nights, city, days are not defined. You used those names to define the input parameters but that does not define those variables outside the functions where they are used.
In other words
def someFunction(inputP):
#here inputP is defined
...
#her inputP is not defined
To return to your question you must assign the returned value to those variables:
nights = hotel_cost(int(raw_input('How many nights will you be staying? ')))
city = plane_cost(raw_input('\n1. O.R. Tambo International\n2. Capetown International\n3. King Shaka International\nWhere you flying to? '))
days = car_rental(int(raw_input('How many days will you need a car for?: ')))
Since it is easy to get lost in Python I suggest using different names for variables in different scope: do not use nights for example in hotel_cost then twice in holiday_cost and then another time in the global scope.
Cheers!
You have to save the values you asked in variables:
nights=hotel_cost(int(raw_input('How many nights will you be staying? ')))
city=plane_cost(raw_input('\n1. O.R. Tambo International\n2. Capetown
International\n3. King Shaka International\nWhere you flying to? '))
days=car_rental(int(raw_input('How many days will you need a car for?: ')))
total = holiday_cost(nights, city, days)
Regards!

I am having problems with my elif statements

I'm programming a game to try and improve my skills in python. In this part of the code I am trying to program a shop with a money system testing one variable against 5 different possible answers
while True:
choice=str(input("What would you like to buy? (Type in 'nothing' when you don't want anymore items) "))
if choice!="health potion" and "strength potion" and "strength booster" and "armour piece" and "nothing":
print()
next_line=input("I do not understand what you wrote. Try again please ")
print()
elif choice=="nothing":
next_line=input("The merchant says 'Thanks for business' ")
print()
break
elif choice=="health potion":
gold=gold-10
if gold<0:
gold=gold+10
next_line=input("Sorry but you don't have enough gold ")
print()
else:
next_line=input("You bought a health potion ")
health_potions=health_potions+1
next_line=input("You now have "+str(gold)+" gold coins ")
print()
elif choice=="strength potion":
gold=gold-15
if gold<0:
gold=gold+15
next_line=input("Sorry but you don't have enough gold ")
print()
else:
next_line=input("You bought a strength potion ")
strength_potions=strength_potions+1
next_line=input("You now have "+str(gold)+" gold coins ")
print()
elif choice=="strength booster":
gold=gold-45
if gold<0:
gold=gold+45
next_line=input("Sorry but you don't have enough gold ")
print()
else:
next_line=input("You boosted your strength ")
strength_booster=strength_booster+1
next_line=input("You now have "+str(gold)+" gold coins ")
print()
elif choice=="armour piece":
gold=gold-30
if gold<0:
gold=gold+30
next_line=input("Sorry but you don't have enough gold ")
print()
else:
next_line=input("You bought an armour piece ")
armour=armour+1
next_line=input("You now have "+str(gold)+" gold coins ")
print()
When you input health potion the code goes on like normal but with the other inputs it goes to this part of the code
if choice!="health potion" and "strength potion" and "strength booster" and "armour piece" and "nothing":
print()
next_line=input("I do not understand what you wrote. Try again please ")
print()
For fun, here is a significantly more advanced version.
Don't worry if it doesn't all make sense right away; try tracing through it and figuring out how it works. Once you fully understand it you will have a much better grasp of Python!
class Character:
def __init__(self, name, health=50, strength=20, gold=200, inventory=None):
"""
Create a new character
inventory is a list of items (may have repeats)
"""
self.name = name
self.health = health
self.strength = strength
self.gold = gold
self.inventory = [] if inventory is None else list(inventory)
def buy(self, item):
"""
Buy an item
"""
if self.gold >= item.cost:
print(item.buy_response.format(name=item.name, cost=item.cost)) # print acceptance
self.gold -= item.cost # pay gold
item.buy_action(self) # apply purchased item to character
return True
else:
print("Sorry but you don't have enough gold.")
return False
class Item:
def __init__(self, name, cost, buy_response="You bought a {name} for {cost} GP", buy_action=None):
# store values
self.name = name
self.cost = cost
# what to print on a successful purchase
self.buy_response = buy_response
# apply a purchased item to the character
self.buy_action = self.make_buy_action() if buy_action is None else buy_action
def make_buy_action(self):
def buy_action(char):
"""
Purchase default action: add item to character inventory
"""
char.inventory.append(self)
return buy_action
#staticmethod
def buy_strength_booster(char):
"""
Purchase strength booster action: increase character strength
"""
char.strength += 1
def __str__(self):
return self.name
class Shop:
def __init__(self, name, *inventory):
"""
Create a shop
inventory is a list of (num, item); if num is None the store has an unlimited supply
"""
self.name = name
self.inventory = {item.name:(num, item) for num,item in inventory}
def visit(self, char):
"""
Serve a customer
"""
print("\nHowdy, {}, and welcome to {}!".format(char.name, self.name))
while True:
print("\nWhat would you like to buy today? (type 'list' to see what's available or 'done' to leave)")
opt = input("{} GP> ".format(char.gold)).strip().lower()
if opt == 'done':
print("Have a great day, and c'mon back when you've got more gold!")
break
elif opt == 'list':
item_names = sorted(name for name, (num, item) in self.inventory.items() if num is None or num > 0)
if item_names:
print(", ".join(item_names))
else:
print("Huh - looks like we're all sold out. Try again next week!")
break
elif opt in self.inventory:
num, item = self.inventory[opt]
if num is None or num > 0:
yn = input("That's {} GP. You want it? [Y/n]".format(item.cost)).strip().lower()
if yn in {'', 'y', 'yes'}:
if char.buy(item) and num is not None:
self.inventory[opt] = (num - 1, item)
else:
print("(scowling, the proprietor stuffs the {} back under the counter)".format(item.name))
else:
print("'Fraid we're all out of those.")
else:
print("Sorry, hain't had one o' those around in a coon's age!")
def main():
# stock the store
shop = Shop("Dwarven Dave's Delving Deal Depot",
(6, Item("health potion", 10)),
(6, Item("strength potion", 15)),
(3, Item("strength booster", 45, "You boosted your strength!", Item.buy_strength_booster)),
(None, Item("armor piece", 30)) # unlimited stock
)
# create a buyer
jeff = Character("Jeff")
# visit the store
shop.visit(jeff)
if __name__ == "__main__":
main()
Your issue is with this statement:
if choice!="health potion" and "strength potion" and "strength booster" and "armour piece" and "nothing":
Comparing strings like this doesn't work. You need to make sure it isn't in an array of the strings
if choice not in ("health potion","strength potion","strength booster","armour piece","nothing"):
Otherwise it will always be true, so the first statement will always execute.

Python pick item from list of classes

So first I'm trying to make a class, which holds an item's name, price, and quantity available. Then I wanted to make a function that will deduct the quantity sold to a buyer after they enter the amount they are buying, and then calculate the total price.
Now to add on top of that, I am trying to have the user select from a list of items.
The problem is it seem I seem to be getting errors around the time the program starts running the 'buy' function.
class Retail:
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy (self):
print ("How many are you buying?")
quant = int(input("Amount: "))
unitsOnHand -= quant
subto = price * quant
total = subto * 1.08
print ("There are now ", unitsOnHand, " left")
print ("The total price is $", total)
box = Retail(4.95, 20, "Boxes")
paper =Retail(1.99, 50, "Big Stacks of Paper")
staples =Retail(1.00, 200, "Staples")
ilist = (box, paper, staples)
print ("Which are you buying? ", [box.description, paper.description, staples.description])
ioi = input("Please use the exact word name: ")
if ioi == 'box':
Retail.buy(ilist[0])
elif ioi == 'paper':
Retail.buy(ilist[1])
elif ioi == 'staples':
Retail.buy(ilist[2])
The error I get when I tried to run it is
Traceback (most recent call last):
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 22, in <module>
Retail.buy(ilist[0])
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 9, in buy
unitsOnHand -= quant
UnboundLocalError: local variable 'unitsOnHand' referenced before assignment
I'm guessing is that it doesn't see the values I already assigned to the item, and if that is the case, how do I get it to?
Others have pointed out your error, but the other thing that is wrong is your buy call needs to be done on an instance of the object, not the class itself. In other words, right now you are executing buy on the Retail class where you need to execute it on instance (objects) of the class.
I have another suggestion to help organize your code. Use a dictionary to map the keys to the various objects to make your loop a bit cleaner. Putting all that together (and some other checks), here is an updated version of your class:
class Retail(object):
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy(self):
if self.unitsOnHand == 0:
print('Sorry, we are all out of {} right now.'.format(self.description))
return
print("How many are you buying? We have {}".format(self.unitsOnHand))
quant = int(input("Amount: "))
while quant > self.unitsOnHand:
print('Sorry, we only have {} left'.format(self.unitsOnHand))
quant = int(input("Amount: "))
self.unitsOnHand -= quant
subto = self.price * quant
total = subto * 1.08
print("There are now {} left".format(self.unitsOnHand))
print("The total price is ${}".format(total))
return
stock = {}
stock['box'] = Retail(4.95, 20, "Boxes")
stock['paper'] = Retail(1.99, 50, "Big Stacks of Paper")
stock['staples'] = Retail(1.00, 200, "Staples")
print("Which are you buying? {}".format(','.join(stock.keys())))
ioi = input("Please use the exact word name: ")
while ioi not in stock:
print("Sorry, we do not have any {} right now.".format(ioi))
print("Which are you buying? {}".format(','.join(stock.keys())))
ioi = input("Please use the exact word name: ")
stock[ioi].buy()

Calculations in module / While Loop / Transferring Variables

I'm very new to python and I'm stuck in some basic problems.
I can't seem to be able to put most of my calculations in a module. If I do, the results are not transferable and they will always show up as 0.0.
Once I'm able to put my calculations in a module, I can put the module inside a loop and ask the user if he wants to repeat the action.
This is my main issue too :: I want to "store" the output (displayResults) of each of the items (item number, price, etc) and print all of them once the loop is cancelled.
Thanks! I'm having a pretty difficult time trying to figure this out.
Here is my code:
#Mateo Marquez
#Oct. 8th, 2012
#P.O.S information system assigment
#
#Define Global Variables
TAX = 0.6
YELLOW_TAG = 0.10
BLUE_TAG = 0.20
RED_TAG = 0.25
GREEN_TAG = 0
#Main Module
def main():
tax_fee = 0.0
total_price = 0.0
introUser()
# I want this to be the mainCalc() function and return results.
productNumber=raw_input("Please enter the Product Number: ")
cost=float(raw_input("Please enter the cost of the selected product: "))
print " "
print "As you might have noticed, our discounts are color coded"
print "Yellow is 10%, Blue is 20% & Red is 25%"
print " "
tagDiscount=raw_input("Please enter the color tag: (yellow, blue, red or none)")
if tagDiscount == 'yellow':
print " "
print "You get a 10% discount"
total_price = (YELLOW_TAG*cost)
if tagDiscount == 'blue':
print " "
print "You get a 20% discount"
total_price = (BLUE_TAG*cost)
if tagDiscount == 'red':
print " "
print "You get a 25% discount"
total_price = (RED_TAG*cost)
if tagDiscount == 'none':
print " "
print "No discount for you!"
total_price = 0
print " "
print "~Remember~ this weekend is Tax Free in most of the country"
print "Green Tags designate if the product is tax free"
tagDiscount=raw_input("Does your product has a Green Tag? (yes or no)")
if tagDiscount == 'yes':
print " "
print "Good! your product is tax free"
tax_fee = 0
if tagDiscount == 'no':
print " "
print "I'm sorry, product", productNumber, "requires regular tax"
tax_fee = (TAX*total_price)
#I want this to be the end of the mainCalc() function
displayResults(total_price, tax_fee, cost, productNumber)
#Introduction function
def introUser():
print "Welcome to Wannabee's"
print "I'll gladly help you with your price question"
print "Let's start"
print " "
#Display results function
def displayResults(total_price, tax_fee, cost, productNumber):
print " "
print "Your Product Number: ", productNumber
print "Listed price of your product: $", cost
print "Your discount: $", total_price
print "Your Tax amount: $", tax_fee
print "Your grand total: $", (cost - total_price - tax_fee)
print " "
print "Your savings: ", ((cost-total_price)/cost*100),"%!"
main()
In order to save values used by related routines, put the variables and the routines that use them in a class. The following code defines a "POS" class and two method routines that share its variables. The "self." notation in the methods indicates a class variable that is saved in the instance "p" that is created when the class is instantiated with p = POS().
The example illustrates how the variables are stored; you'll need to adjust the inputs and print statements as needed (they're in Python 3 here). If you want to store the items as they are input and print them at the end, create an empty list in __init__, add a tuple to the list in mainCalc(), and print out each of the list items in displayResults().
class POS:
def __init__(self):
self.taxrate = 0.06
self.disc = {"": 0.0, "yellow": 0.10, "blue": 0.20, "red": 0.25}
self.total = 0
self.savings = 0
self.tax = 0
def mainCalc(self, item, qty, cost, tag, taxable):
print(qty, "* Item", item, "# ${:.2f}".format(cost),
"= ${:.2f}".format(qty*cost))
discount = cost * self.disc[tag]
if (tag):
print(" You get a", int(100*self.disc[tag]),
"% discount ${:.2f}".format(discount), "for", tag, "tag")
self.total += qty * (cost - discount)
self.savings += discount
if (taxable == "yes"):
tax = qty * cost * self.taxrate
self.tax += tax
print(" tax ${:.2f}".format(tax))
else:
print(" tax free")
def displayResults(self):
print("----------------")
print("Your total: ${:.2f}".format(self.total))
print("Your savings: ${:.2f}".format(self.savings))
print("Your total tax: ${:.2f}".format(self.tax))
print("Grand total: ${:.2f}".format(self.total + self.tax))
return
p = POS()
# Item Qty Price Tag Taxable
items = [(1492, 1, 1.95, "yellow", "yes"),
(1524, 2, 4.50, "blue", "no"),
(2843, 1, 6.95, "blue", "yes"),
(1824, 3, 2.29, "", "yes")]
for i in items:
p.mainCalc(*i)
p.displayResults()
Running the example produces:
1 * Item 1492 # $1.95 = $1.95
You get a 10 % discount $0.20 for yellow tag
tax $0.12
2 * Item 1524 # $4.50 = $9.00
You get a 20 % discount $0.90 for blue tag
tax free
1 * Item 2843 # $6.95 = $6.95
You get a 20 % discount $1.39 for blue tag
tax $0.42
3 * Item 1824 # $2.29 = $6.87
tax $0.41
----------------
Your total: $21.39
Your savings: $2.49
Your total tax: $0.95
Grand total: $22.33
You should consider the following constraints:
A function can only be called after it has been defined by a def statement (your call to displayResults.
Functions cannot access variables that are defined locally in the body of another function definition.
To improve your code, either think about how the program should flow from an overall point of view, or use a class as suggested in Dave's answer.

Categories