Calculating a bill and store the sum to a daily_income - python

So I'm very new to Python programming and just testing out some stuff in classes and methods.
Im writing a program for a restaurant that have 4 dictionaries that contains key=food and value=price
The dict's are stored in brunch_items, early_bird_items, dinner_items and kids_items, and then I created a object for each of them to my Menu class.
from main import *
dinner_items = {
'crostini with eggplant caponata': 13.00,
'caesar salad': 16.00,
'pizza with quattro formaggi': 11.00,
'duck ragu': 19.50,
'mushroom ravioli (vegan)': 13.50, 'coffee': 2.00, 'espresso': 3.00,
}
kids_items = {
'chicken nuggets': 6.50,
'fusilli with wild mushrooms': 12.00,
'apple juice': 3.00
}
brunch_menu = Menu("Brunch Menu", brunch_items, 1100, 1600)
early_bird_menu = Menu("Early Bird Menu", early_bird_items, 1500, 1800)
dinner_menu = Menu("Dinner Menu", dinner_items, 1700, 1100)
kids_menu = Menu("Kids Menu", kids_items, 1100, 2100)
print(brunch_menu.calculate_bill(["pancakes", "waffles"]))
In the Menu class have the method that returns the different menus and when they are available.
The next method is calculating the bill and return the price for the items.
Output from printing the bill: 16.5
class Menu:
def __init__(self, name, items, start_time, end_time):
self.name = name
self.items = items
self.start_time = start_time
self.end_time = end_time
self.daily_income = 0
def __repr__(self):
return "{} is available from {} - {}".format(self.name, self.start_time, self.end_time)
def calculate_bill(self, purchased_items):
bill = 0
for purchased_item in purchased_items:
if (purchased_item in self.items):
bill += self.items[purchased_item]
return bill
def total_income(self, purchased_items):
return self.daily_income + purchased_items
I dont know where this is going, but the problem is to define a method that takes the calculated bill and store it to a daily income/profit from the purchased items. The idea is to store the total sum from bills
I tried to make self.daily_income = 0 and eventually return that to a variable that keep tracking the payments
Any suggestions to help out?

There are some modeling choices that you have made that I think you will want to revisit, but with light changes to your code you can get a running total by moving daily_income from an instance variable to a shared variable.
class Menu:
daily_income = 0 # shared between all instances
def __init__(self, name, items, start_time, end_time):
self.name = name
self.items = items
self.start_time = start_time
self.end_time = end_time
def __repr__(self):
return "{} is available from {} - {}".format(self.name, self.start_time, self.end_time)
def calculate_bill(self, purchased_items):
bill = 0
for purchased_item in purchased_items:
if (purchased_item in self.items):
bill += self.items[purchased_item]
Menu.daily_income + bill ## Update the shared total
return bill
dinner_items = {
'crostini with eggplant caponata': 13.00,
'caesar salad': 16.00,
'pizza with quattro formaggi': 11.00,
'duck ragu': 19.50,
'mushroom ravioli (vegan)': 13.50, 'coffee': 2.00, 'espresso': 3.00,
}
kids_items = {
'chicken nuggets': 6.50,
'fusilli with wild mushrooms': 12.00,
'apple juice': 3.00
}
## ---------------------------
## Simulate table A
## ---------------------------
my_bill = Menu("Dinner Menu", dinner_items, 1700, 1100).calculate_bill(["caesar salad", "duck ragu"])
my_bill += Menu("Kids Menu", kids_items, 1100, 2100).calculate_bill(["chicken nuggets"])
Menu.daily_income += my_bill
print(f"Total Table Bill: ${my_bill}. Our revenue so far: ${Menu.daily_income}")
## ---------------------------
## ---------------------------
## Simulate table B
## ---------------------------
my_bill = Menu("Dinner Menu", dinner_items, 1700, 1100).calculate_bill(["pizza with quattro formaggi"])
Menu.daily_income += my_bill
print(f"Total Table Bill: ${my_bill}. Our revenue so far: ${Menu.daily_income}")
## ---------------------------
That should give you:
Total Table Bill: $42.0. Our revenue so far: $42.0
Total Table Bill: $11.0. Our revenue so far: $53.0

Related

I want to print out an itemized receipt with total cost

I am a beginner in programming and I'm working on the projects in Automate the Boring Stuff with Python, In the book there is a project to create a sandwich, then return the total cost. I want to add to my program by providing an itemized receipt. For example, if I put in an order for 1 sandwich with wheat and chicken and 3 sandwiches with white and turkey, the receipt should show something like this (I will format it better when I figure it out):
1 sandwich ---3.5
wheat, chicken
3 sandwich ---10.5.
white, turkey
Total --- 14.00
My challenge is storing the different sandwich orders into different variables and printing them out at the end.
My code below:
menu = {
'wheat': 1.5, 'white': 1, 'sourdough': 2,
'chicken': 2, 'turkey': 2.5, 'ham': 2, 'tofu': 3,
'cheddar': 0.5, 'mozzarella': 0.25, 'american': 0.5,
'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.5, 'tomato': 0.5
}
total = 0.0
subtotal = 0.0
while True:
order = {}
print('What bread would you like?')
order['bread'] = pyip.inputChoice(['wheat', 'white', 'sourdough'])
print('How about for your protein?')
order['protein'] = pyip.inputChoice(['chicken', 'turkey', 'ham', 'tofu'])
wantCheese = pyip.inputYesNo('Would you like cheese on the sandwich?')
if wantCheese == 'yes':
order['cheese'] = pyip.inputChoice(['cheddar', 'mozzarella', 'american'])
wantToppings = pyip.inputYesNo('Would you like to add extra toppings?')
if wantToppings == 'yes':
while True:
order['side'] = pyip.inputChoice(['mayo', 'mustard', 'lettuce', 'tomato'])
anotherTopping = pyip.inputYesNo('Would you like another topping?')
if anotherTopping == 'no':
break
orderNumber = pyip.inputInt('How many of those sandwiches would you like? ', min = 1)
for choice in order:
if order[choice] in menu.keys():
subtotal += menu[order[choice]]
total *= orderNumber
total += subtotal
subtotal = 0
anotherOrder = pyip.inputYesNo('Would you like to order another sandwich?')
if anotherOrder == 'no':
break
print(total)
Adjust the following as you see fit. FYI, while coding this up I had "let's get this to work" in mind as opposed to "let's make this as efficient as possible". Moreover, you should format the receipt however you like.
Importantly, I created a list called orders just before the while that will be used to store orders. The form of the elements of orders will be 3-tuples where the first element of the 3-tuple records orderNumber, the third element records the subtotal, and the second element is an order dictionary, just as in your original code, except order["side"] will be a list as this allows for multiple additional toppings to be added. For the sample output below, orders is
[(2, {'bread': 'wheat', 'protein': 'chicken', 'cheese': 'cheddar', 'side': ['mustard', 'lettuce']}, 9.5), (1, {'bread': 'sourdough', 'protein': 'turkey', 'side': []}, 4.5)]
As you can see, there are 2 orders of 'wheat', 'chicken', 'cheddar', 'mustard', 'lettuce' (subtotal 9.5) and 1 order of 'sourdough', 'turkey' (subtotal 4.5).
I hope this helps. Any questions please let me know.
import pyinputplus as pyip
menu = {'wheat': 1.5, 'white': 1, 'sourdough': 2,
'chicken': 2, 'turkey': 2.5, 'ham': 2, 'tofu': 3,
'cheddar': 0.5, 'mozzarella': 0.25, 'american': 0.5,
'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.5, 'tomato': 0.5
}
orders = []
while True:
order = {}
# choose bread
print("What bread would you like?")
order['bread'] = pyip.inputChoice(['wheat', 'white', 'sourdough'])
# choose protein
print("How about for your protein?")
order['protein'] = pyip.inputChoice(['chicken', 'turkey', 'ham', 'tofu'])
# choose cheese
wantCheese = pyip.inputYesNo("Would you like cheese on the sandwich?")
if wantCheese == 'yes':
order['cheese'] = pyip.inputChoice(['cheddar', 'mozzarella', 'american'])
# choose extra toppings
order["side"] = []
wantToppings = pyip.inputYesNo("Would you like to add extra toppings?")
if wantToppings == 'yes':
while True:
order["side"].append(pyip.inputChoice(
['mayo', 'mustard', 'lettuce', 'tomato']))
anotherTopping = pyip.inputYesNo("Would you like another topping?")
if anotherTopping == 'no':
break
# order number
orderNumber = pyip.inputInt(
"How many of those sandwiches would you like?", min = 1)
# subtotal
subtotal = sum(menu[order[key]] for key in order if key != 'side')
subtotal += sum(menu[j] for j in order['side'])
subtotal *= orderNumber
# add 3-tuple to orders list
orders.append((orderNumber, order, subtotal))
# another order?
anotherOrder = pyip.inputYesNo("Would you like to order another sandwich?")
if anotherOrder == 'no':
break
# add subtotals to form total
total = sum(order[2] for order in orders)
# print orders (for programmer use)
print(f"\nOrders: {orders}")
# print receipt
print(f"\nReceipt\n")
for order in orders:
print(f"{order[0]} sandwich ---{order[2]}")
print(" ", end = "")
for key in order[1]:
if isinstance(order[1][key], list):
for x in order[1][key]:
print(x, end = ", ")
else:
print(order[1][key], end = ", ")
print("\n")
print(f"Total --- {total}")
Sample output:
Receipt
2 sandwich ---9.5
wheat, chicken, cheddar, mustard, lettuce,
1 sandwich ---4.5
sourdough, turkey,
Total --- 14.0

How To Add Specific Keys In Nested Dictionary In Python

I may be formatting this dictionary wrong (my first time doing this)
I have a dictionary of every province with corrected ID and added it to value "Canada". I'm trying to add the population of ALL the provinces in the nested dictionary
ontario = dict(capital="Toronto", largest="Toronto", population=14826276)
quebec = dict(capital="Quebec City", largest="Montreal", population=8604495)
nova_Scotia = dict(capital="Halifax", largest='Halifax', population=992055)
new_Brunswick = dict(capital="Fredricton", largest='Moncton', population=789225)
manitoba = dict(capital="Winnipeg", largest="Winnipeg", population=1383765)
canada = {ontario, quebec, nova_Scotia, new_brunswick, manitoba, british_columbia, prince_edward_island, saskatchewan, alberta, newfoundland_and_labrador}
for key, value in canada.items():
if value and 'population' in value.keys():
# Adding all values of population to receive total population of canada
sum += value['population']
print(sum)
thanks again in advance.
You didn't create dictionary but set (which doesn't have keys)
To create dictionary you would need keys like
canada = {1:ontario, 2:quebec, 3:nova_scotia, 4:new_brunswick, 5:manitoba}
canada = {"Ontario":ontario, "Quebec":quebec, "Nova Scotia":nova_scotia, "New Brunswick":new_brunswick, "Manitoba":manitoba}
and then you can use canada.items() and sum population
(I use variable total because there is function sum())
# --- before `for`-loop ---
total = 0
# --- `for`-loop ---
for key, value in canada.items():
total += value['population']
# --- after `for`-loop ---
print(total)
or shorter
total = sum(value['population'] for value in canada.values())
and then you can add to this dictionary
canada['total'] = total
Full code:
ontario = dict(capital="Toronto", largest="Toronto", population=14826276)
quebec = dict(capital="Quebec City", largest="Montreal", population=8604495)
nova_scotia = dict(capital="Halifax", largest='Halifax', population=992055)
new_brunswick = dict(capital="Fredricton", largest='Moncton', population=789225)
manitoba = dict(capital="Winnipeg", largest="Winnipeg", population=1383765)
canada = {1:ontario, 2:quebec, 3:nova_scotia, 4:new_brunswick, 5:manitoba}#, british_columbia, prince_edward_island, saskatchewan, alberta, newfoundland_and_labrador
total = 0
for key, value in canada.items():
total += value['population']
print(total)
#total = sum(value['population'] for value in canada.values())
canada['total'] = total
print(canada)
I only added the listed 5 provinces into the nested dictionary.
I used a for loop to calculate the total population of Canada (the
sum of the 5 listed provinces).
Note that my nested dictionary has the same format as a normal dictionary,
"a key : value" --> "1 : ontario"
ontario = dict(capital="Toronto", largest="Toronto", population=14826276)
quebec = dict(capital="Quebec City", largest="Montreal", population=8604495)
nova_Scotia = dict(capital="Halifax", largest='Halifax', population=992055)
new_Brunswick = dict(capital="Fredricton", largest='Moncton', population=789225)
manitoba = dict(capital="Winnipeg", largest="Winnipeg", population=1383765)
canada = {1:ontario, 2:quebec, 3:nova_Scotia, 4:new_Brunswick, 5:manitoba}
#canada = {ontario, quebec, nova_Scotia, new_brunswick, manitoba, british_columbia, prince_edward_island, saskatchewan, alberta, newfoundland_and_labrador}
sum = 0
for providence in canada:
# Adding all values of population to receive total population of canada
sum += (canada[providence]["population"])
print(sum)
Try this one.
ontario = dict(capital="Toronto", largest="Toronto", population=14826276)
quebec = dict(capital="Quebec City", largest="Montreal", population=8604495)
nova_Scotia = dict(capital="Halifax", largest='Halifax', population=992055)
new_Brunswick = dict(capital="Fredricton", largest='Moncton', population=789225)
manitoba = dict(capital="Winnipeg", largest="Winnipeg", population=1383765)
canada_list = [ontario, quebec, nova_Scotia, new_Brunswick, manitoba]
total = 0
for item in canada_list:
# Adding all values of population to receive total population of canada
total += item.get('population', 0)
print("Total: {}".format(total))
Output:
Total: 26595816

cascading dropdown shows dictionary/array - Python (Jupyter Notebook)

I am trying to create a series of dropdown menus on Jupyter Notebook.
The first few dropdown lists work fine, but it starts to go wonky on the last one, with the output being read as a string instead of a dictionary
Code as follows:
#Initialise GUI
from ipywidgets import interact,Dropdown
import ipywidgets as widgets
#Initialise Dictionaries
NAICSd = {"21-Mining,Quarrying,and oil and gas extraction(8)":0.08,
"11-Agriculture,forestry,fishing and hunting(9)":0.09,
"55-Management of companies and enterprises(10)":0.08,
"62-Healthcare and social assistance(10)":0.1,
"22-Utilities(14)":0.14,
"92-Public Administration(15)":0.15,
"54-Professional,scientific and technical services(19)":0.19,
"42-Wholesale trade(19)":0.19,
"31-Manufacturing(19)":0.19,
"32-Manufacturing(16)":0.16,
"33-Manufacturing(14)":0.14,
"81-Other Sevices Exept Public Administration(20)":0.2,
"71-Arts,Entertainment and Recreation(21)":0.21,
"72-Accommodation and Food Services(22)":0.22,
"44-Retail Trade(22)":0.22,
"45-Retail Trade(23)":0.23,
"23-Construction(23)":0.23,
"56-Administrative/Support & Waste Management/Remediation Service(24)":0.24,
"61-Educational Services(24)":0.24,
"51-Information (25)":0.25,
"48-Transportation and warehousing(27)":0.27,
"49-Transportation and warehousing(23)":0.23,
"52-Finance and Insurance(28)":0.28,
"53-Real Estate and rental and leasing(29)":0.29}
Stated = {"Undefined(28)":0.28,
"Alaska(10)":0.1,
"Alabama(18)":0.18,
"Arkansas(18)":0.18,
"Arizona(20)":0.2,
"California(20)":0.2,
"Colorado(18)":0.18,
"Connecticut(13)":0.13,
"D.C.(8)":0.08,
"Delaware(18)":0.18,
"Florida(28)":0.28,
"Georgia(27)":0.27,
"Hawaii(16)":0.16,
"Iowa(13)":0.13,
"Idaho(15)":0.15,
"Illonois(23)":0.23,
"Indiana(18)":0.18,
"Kansas(13)":0.13,
"Kentucy(20)":0.20,
"Louisiana(18)":0.18,
"Massachusetts(15)":0.15,
"Maryland(20)":0.20,
"Maine(9)":0.09,
"Michigan(23)":0.23,
"Minnesota(13)":0.13,
"Missouri(15)":0.15,
"Missisipi(15)":0.15,
"Montana(8)":0.08,
"North Carolina(20)":0.2,
"North Dakota(8)":0.08,
"Nebraska(15)":0.15,
"New Hampshire(10)":0.1,
"New Jersey(20)":0.2,
"New Mexico(10)":0.1,
"Nevada(23)":0.23,
"New York(20)":0.2,
"Ohio(18)":0.18,
"Oklahoma(13)":0.13,
"Oregon(17)":0.17,
"Pennsylvania(15)":0.15,
"Rhode Island(8)":0.08,
"South Carolina(20)":0.2,
"South Dakota(8)":0.08,
"Tennesee(23)":0.23,
"Texas(20)":0.2,
"Utah(18)":0.18,
"Virginia(19)":0.19,
"Vermont(8)":0.08,
"Washington(13)":0.13,
"Wisconsin(15)":0.15,
"West Virginia(15)":0.15,
"Wyoming(8)":0.18
}
Businessd = {"New Business <2 years(18.98)":0.1898,
"Normal Business >= 2 years (17.36)":0.1736}
BackedRealEstated = {"Yes(1.64)":0.0164,
"No(21.16)":0.2116}
IsRecessiond ={"Yes(32.21)":0.3221,
"No(16.63)":0.1663}
SBARatiod = {"More than 50%(25)":0.25,
"50% or less(40)":0.4}
NAICSList = Dropdown(options = NAICSd)
StateList = Dropdown(options = Stated)
BusinessList = Dropdown(options = Businessd)
BackedRealEstateList = Dropdown(options = BackedRealEstated)
IsRecessionList = Dropdown(options = IsRecessiond)
SBARatioList = Dropdown(option = SBARatiod)
#interact(Sector = NAICSList, US_State=StateList, New_Business=BusinessList, Real_Estate_Backed=BackedRealEstateList,
Recession = IsRecessionList, Guarantee_Ratio = SBARatioList)
def print_dropdown(Sector, US_State, New_Business, Real_Estate_Backed, Recession, Guarantee_Ratio):
NAICSList.options = NAICSd
StateList.options = Stated
BusinessList = Businessd
BackedRealEstateList = BackedRealEstated
IsRecessionList = IsRecessiond
Guarantee_Ratio = SBARatiod
print(Sector, US_State, New_Business, Real_Estate_Backed, Recession, Guarantee_Ratio)
Sector, US_State, New_Business, Real_Estate_Backed and Recession all return a float, which is what I want. But Guarantee_Ratio returns '{'More than 50%(25)': 0.25, '50% or less(40)': 0.4}'
I saw my problem. I confused the Guarantee_Ratio variable with the list
def print_dropdown(Sector, US_State, New_Business, Real_Estate_Backed, Recession, Guarantee_Ratio):
NAICSList = NAICSd
StateList = Stated
BusinessList = Businessd
BackedRealEstateList = BackedRealEstated
IsRecessionList = IsRecessiond
SBARatioList = SBARatiod
print(Sector, US_State, New_Business, Real_Estate_Backed, Recession, Guarantee_Ratio)]

Python Classes and Object assignment

I need to write a program that does the following:
First, find the County that has the highest turnout, i.e. the highest percentage of the
population who voted, using the objects’ population and voters attributes
Then, return a tuple containing the name of the County with the highest turnout and the
percentage of the population who voted, in that order; the percentage should be
represented as a number between 0 and 1.
I took a crack at it, but am getting the following error:
Error on line 19:
allegheny = County("allegheny", 1000490, 645469)
TypeError: object() takes no parameters
Here is what I've done so far. Thank you so much for your help.
class County:
def __innit__(self, innit_name, innit_population, innit_voters) :
self.name = innit_name
self.population = innit_population
self.voters = innit_voters
def highest_turnout(data) :
highest_turnout = data[0]
for County in data:
if (county.voters / county.population) > (highest_turnout.voters / highest_turnout.population):
highest_turnout = county
return highest_turnout
# your program will be evaluated using these objects
# it is okay to change/remove these lines but your program
# will be evaluated using these as inputs
allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]
result = highest_turnout(data) # do not change this line!
print(result) # prints the output of the function
# do not remove this line!
def __innit__(self, innit_name, innit_population, innit_voters) :
You mispelled __init__

python: local variable referenced before assignment error

I am completing a text based game for an intro to python class. It is not complete but I was working on the main_menu function and the functions called within the main_menu function when I ran into this error message. I have encountered this error several times in my learning experience and it was usually attributed to a basic mistake when assigning variables, but this one has me stumped...
This is the script in question (lines in traceback commented in BOLD):
import random
from sys import exit
# Item variables
coal = ('Coal', 'some coal which can be used in a furnace.')
eng_key = ('Key', 'a key to a house.')
bomb = ('Bomb', 'a combustible device which creates a powerfull explosion. Possibly used for demolition...')
tonic = ('Tonic', 'a weak healing tonic. Adds \'5\' health points.')
sTonic = ('Super Tonic', 'a strong healing tonic. Adds \'10\' health points.')
# LOCATIONS
# Below are the possible locations you can 'travel' to, along with a title (first item in tuple), a description, any items that might be found in the location which can be discovered and entered into 'inventory' through 'search' command
# location variable = (title, description, item for discovery)
sub_base = ('Sub-Base', 'This is DeepBlue\'s base of operations in the Atlantis excavation zone. Your submarine is docked ahead', 'nothing useful here.')
cave = ('Underwater Cave', 'You have entered the mouth of an underwater cave with your sub.', 'nothing useful here.')
cemetery = ('Cemetery Chamber', 'You are in a large chamber within the cave. This seems to be a cemetery. There are symmetrically lined mounds of dirt, with obelisks at the head.', 'nothing useful here.')
city_gate = ('City Gate', 'You stand at a crossroad of sorts, at the bottom of an upward sloping ramp.', 'nothing useful here.')
city_outskirts = ('City Outskirts', 'You find yourself just outside the city walls.', 'nothing useful here.')
castle_outskirts = ('Rear of Castle Ruins', 'You are standing at the rear of the castle ruins. There is a layer of rubble blocking the way, but you can clearly see a passage leading inside. Perhaps you can devise a way to move it...', 'nothing useful here.')
castle_inside = ('Inside the Grand Castle of Atlantis', 'You have made it inside of the castle. All the advanced knowledge of the Atlanteans is at your disposal.', 'nothing useful here.')
city_block0 = ('Beginning of Main Avenue in City', 'You are standing at the beginning of the main avenue of the city.', 'nothing useful here.')
ruins1 = ('Rubble of Dilapidated House', 'You are standing in the middle of the ruins of what seems to have been a house.', tonic)
mystic_house = ('Mystic House', 'You are standing inside the city Mystic\'s house.', sTonic)
city_block1 = ('Second Block in City', 'You have moved to the second block of the city\'s main avenue.', 'nothing useful here.')
abandoned_house = ('Abandoned House', 'You are standing in the middle of an abandoned house.', eng_key)
blacksmith_house = ('Blacksmith\'s House', 'You are standing in what seems to be a blacksmith\'s building. There is a furnace, iron ore, smith\'s tools and various components for making swords. No coal though...', 'nothing useful here. But with the right items, something can be created here...')
city_block2 = ('Third Block in City', 'You have moved to the third block of the city\'s main avenue.', 'nothing useful here.')
marketplace = ('Abandoned Marketplace', 'You are standing in the middle of an abandoned marketplace. There might be some useful items laying around...', coal)
engineer_house = ('Engineer\'s House', 'You are standing in the engineer\'s house. There might be some useful items lying around...', bomb)
castle_main = ('Castle Main Entrance', 'You are standing in front of the main entrance of a huge castle. The grand entrance is blocked off by massive amounts of rubble. There must be another way in...', 'nothing useful here.')
# ITEMS
# below are the items which may be added to the inventory
items = {
coal: (engineer_house,),
eng_key: (engineer_house,),
bomb: (castle_inside,),
tonic: ('anywhere',),
sTonic: ('anywhere',)
}
# INTERACTIONS(location-based)
# below is a dictionary of events. Each location has certain events which can only take place there.
# interactions dictionary = {location: (use+item response, search response)}
lEvents = {sub_base: (cave,),
cave: (sub_base, cemetery, city_gate),
cemetery: (cave, city_outskirts),
city_gate: (cave, city_outskirts, city_block0),
city_outskirts: (cemetery, castle_outskirts, city_gate),
castle_outskirts: (city_outskirts,castle_inside),
castle_inside: (castle_outskirts,),
city_block0: (city_gate, ruins1, mystic_house, city_block1),
ruins1: (city_block0,),
mystic_house: (city_block0,),
city_block1: (city_block0, abandoned_house, blacksmith_house, city_block2),
abandoned_house: (city_block1,),
blacksmith_house: (city_block1,),
city_block2: (city_block1, marketplace, engineer_house, castle_main),
marketplace: (city_block2,),
engineer_house: (city_block2,),
castle_main: (city_block2,)
}
# TRAVEL OPTIONS
# Below is a dictionary outlining the possible places to travel to depending on where you are currently located, this peice is essential to the travel function
travelOpt = {
sub_base: (cave,),
cave: (sub_base, cemetery, city_gate),
cemetery: (cave, city_outskirts),
city_gate: (cave, city_outskirts, city_block0),
city_outskirts: (cemetery, castle_outskirts, city_gate),
castle_outskirts: (city_outskirts,castle_inside),
castle_inside: (castle_outskirts,),
city_block0: (city_gate, ruins1, mystic_house, city_block1),
ruins1: (city_block0,),
mystic_house: (city_block0,),
city_block1: (city_block0, abandoned_house, blacksmith_house, city_block2),
abandoned_house: (city_block1,),
blacksmith_house: (city_block1,),
city_block2: (city_block1, marketplace, engineer_house, castle_main),
marketplace: (city_block2,),
engineer_house: (city_block2,),
castle_main: (city_block2,)
}
def eHouseAccess(action, location, eHouse):
if eHouse == 'locked':
print "The door is locked! You need to find a key for this door."
travel(location)
else:
location = travelOpt[location][action - 1]
travel(location)
def cInsideAccess(action, location, cInside):
if cInside == 'blocked':
print "The path is blocked by rubble! You need to find a way to clear the rubble."
travel(location)
else:
location = travelOpt[location][action - 1]
travel(location)
def travel(location):
while True:
print "You are in the", location[0]+"."
print location[1]
print 'You can travel to:'
for (i, t) in enumerate(travelOpt[location]):
print i + 1, t[0]
action = raw_input("Pick a destination, or enter 'menu' for the main menu: ")
if action == 'menu':
main_menu(location, inventory, items)
else:
action = int(action)
if travelOpt[location][action - 1] == engineer_house:
eHouseAccess(action, location, eHouse)
elif travelOpt[location][action - 1] == castle_inside:
cInsideAccess(action, location, cInside)
else:
location = travelOpt[location][action - 1]
def main_menu(location, inventory, items):
travel = travel(location) # **this is line 133**
invtry = showInv(inventory)
use = use(items, inventory)
quit = exit(0)
while True:
print "You are in the", location[0]
menu_list = [('Travel', travel), ('Inventory', invtry), ('Use', use), ('Search', search), ('Map', map), ('Quit', quit)]
print "Choose one:"
for (num, t) in enumerate(menu_list):
print num + 1, t[0]
main_choice = int(raw_input("> "))
action = menu_list[main_choice - 1]
action[1]
def search(location):
pass
def map(location):
pass
def showInv(inventory):
if inventory == []:
print "Your inventory is empty"
inv = 'empty'
return inv
else:
for (num, i) in enumerate(inventory):
print num + 1, i
inv = inventory
return inv
def use(items, inventory):
a = showInv(inventory)
if a == 'empty':
print "There is nothing to use."
else:
showInv(inventory)
uItem = int(raw_input("Choose an item to use: "))
location = sub_base
inventory = []
eHouse = 'locked'
cInside = 'blocked'
hp = 20
map = """
Key:
* = indicates a point of entry
______ ______
|Castle|Castle|
|Outsk-| |
|irts |
___|**____|__**__|
| City | | |
|Outsk-| | City |
| irts | | |
_____|*____*|___|*_____|
| | | |
| Grave | | City |
| Yard | | Gates |
|_____**|__|*______|
| |
| Cave |
| |
|__**___|
| |
| Sub- |
| Base |
|_______|
"""
cityMap = """
Key:
* = indicates a point of entry
________
| |
| Castle |
| |
______|___**___|________
| | City | Engin- |
|Market| Block | eer |
|Place * 3 * House |
|______|___ ___|________|
|Aband-| City | Black- |
| oned | Block | smith |
|House * 2 * House |
|______|___**___|________|
| | City | |
|Rubble| Block |Mystic's|
| * 1 * House |
|______|________|________|
"""
name = raw_input("Enter your name: ")
print "Welcome to the Atlantis Excavation Zone, %s." % name
print "Your first day on the job and we already have a new cave for you to map... LUCKY!"
print "The DeepBlue team takes you down to the sub base. Time to get to work."
main_menu(location, inventory, items) # **this is line 236**
And here is the traceback:
Traceback (most recent call last):
File "ex36_2.py", line 236, in <module>
main_menu(location, inventory, items)
File "ex36_2.py", line 133, in main_menu
travel = travel(location)
UnboundLocalError: local variable 'travel' referenced before assignment
I thought the variable had been assigned in line 133. What am I missing here?
The first line
travel = travel(location)
implicitly marks the name travel as local for the whole function. All look-ups for this name look for a local name, including the one on the right-hand side of the cited line. At that time, there is no value assigned to the local name, though, hence the error. There might be a global name travel, but since the compiler identified travel as a local name, it will only look in the local namespace. Use a different name for the local variable.

Categories