I am working on a code to make a coffee machine simulator and I want to add the money paid from each transaction to the money resources in the machine and I can't
PLease help me do it
Thanks
Here is my code:
menu = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee_l": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money":0
}
import os
def check(drink):
if drink == 'espresso':
if resources['water'] >= 50 and resources['coffee'] >= 18:
return "enough"
elif resources['water'] <= 50:
return "Sorry there is not enough water."
elif resources['coffee'] <= 18:
return "Sorry there is not enough coffee."
elif drink=='latte':
if resources['water'] >= 200 and resources['milk'] >= 150 and resources['coffee'] >= 24:
return "enough"
elif resources['water'] < 50:
return "Sorry there is not enough water."
elif resources['coffee'] < 18:
return "Sorry there is not enough coffee."
elif resources['milk'] < 150:
return "Sorry there is not enough milk."
elif drink=='cappuccino':
if resources['water'] >= 250 and resources['milk'] >= 100 and resources['coffee'] >= 24:
return "enough"
elif resources['water'] < 250:
return "Sorry there is not enough water."
elif resources['coffee'] < 24:
return "Sorry there is not enough coffee."
elif resources['milk'] < 100:
return "Sorry there is not enough milk."
def money():
quarter=0.25
dime=0.1
nickel=0.05
pennie=0.01
qu=float(input("Inset quarters: "))
di=float(input("Insert dimes: "))
ni=float(input("Insert nickels: "))
pen=float(input("Insert pennies: "))
total_paid=qu*quarter+di*dime+ni*nickel+pen*pennie
return total_paid
report=f"Water: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}ml\nMoney: {resources['money']}$"
while True:
print("Welcome to the coffee machine.")
m="Espresso = 1.5$\nLatte = 2.5$\nCappuccino = 3.0$\n"
print(m)
choice=input("What would you like? (espresso/latte/cappuccino)(e/l/c): ")
if choice=='e':
# ~ e_w=menu['espresso']['ingredients']['water']
# ~ e_c=menu['espresso']['ingredients']['coffee']
# ~ #print(e_w)
chk=check('espresso')
print(chk)
if chk=="enough":
mo=money()
if mo == menu['espresso']['cost']:
print('Here is your coffee')
elif mo > menu['espresso']['cost']:
print(f'Here is your coffee, and here is your change {round(mo-menu["espresso"]["cost"], 2)} $')
print(f"Money in machine is: {resources['money']}")
elif mo < menu['espresso']['cost']:
print(f'Sorry that\'s not enough money. Money refunded.')
resources['money']=mo+resources['money']
print(f"Money in machine is: {round(resources['money'],2)}")
elif choice=='l':
chk=check('latte')
print(chk)
if chk=="enough":
mo=money()
if mo == menu['latte']['cost']:
print('Here is your coffee')
elif mo > menu['latte']['cost']:
print(f'Here is your coffee, and here is your change {mo-menu["latte"]["cost"]} $')
resources['money']=mo+resources['money']
print(f"Money in machine is: {resources['money']}")
elif mo < menu['latte']['cost']:
print(f'Sorry that\'s not enough money. Money refunded.')
elif choice=='c':
chk=check('cappuccino')
print(chk)
if chk=="enough":
money()
mo=money()
if mo == menu['cappuccino']['cost']:
print('Here is your coffee')
elif mo > menu['cappuccino']['cost']:
print(f'Here is your coffee, and here is your change {mo-menu["cappuccino"]["cost"]} $')
resources['money']=mo+resources['money']
print(f"Money in machine is: {resources['money']}")
elif mo < menu['cappuccino']['cost']:
print(f'Sorry that\'s not enough money. Money refunded.')
elif choice=='report':
print(report)
elif choice=='off':
break
I tried to add it under each if statement in the while loop and it worked but when i entered report there is no money in the machine.
Your variable report is a fixed string. This line:
report=f"Water: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}ml\nMoney: {resources['money']}$"
is executed exactly once and will set report to the string with the values at the time of the execution. What you want instead is a function that, when called, will build the string based on the current resuorces.
def report(resources):
return f"Water: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}ml\nMoney: {resources['money']}$"
Unrelated to your question, but I cannot leave this unmentioned: All your functions should use the data from the dictionary you define at the beginning. For isntance, your check function should look like below and not have any specific numbers in them:
def check(drink):
for ingredient, required_amount in menu[drink]["ingredients"].items():
if resources[ingredient] < required_amount:
return f"Sorry, there is not enough {ingredient}"
return "enough"
This will allow the function to work with new or changed coffee variations without being altered, whereas in your current code, every change has to be done at multiple places.
Last comment: Does your machine accept coins that are broken in half or why are you converting to float as opposed to int?
I see that there has been a answer to your question while I was testing out your code and doing some refactoring. Some of the bits I noticed were that some of the tests did not seem to provide the correct answers. Also, it seemed like there was a bit of repeated instructions happening for the various selections that could be streamlined. With that in mind, I offer up another possible route for your code with the following refactored version.
import os
menu = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee_l": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money":0
}
def check(drink):
response = "Enough"
if drink == 'espresso':
if resources['water'] <= 50:
response = "Sorry there is not enough water."
elif resources['coffee'] <= 18:
response = "Sorry there is not enough coffee."
elif drink ==' latte':
if resources['water'] < 50:
response = "Sorry there is not enough water."
elif resources['coffee'] < 18:
response = "Sorry there is not enough coffee."
elif resources['milk'] < 150:
response = "Sorry there is not enough milk."
elif drink == 'cappuccino':
if resources['water'] < 250:
response = "Sorry there is not enough water."
elif resources['coffee'] < 24:
response = "Sorry there is not enough coffee."
elif resources['milk'] < 100:
response = "Sorry there is not enough milk."
return response
def money():
quarter = 0.25
dime = 0.1
nickel = 0.05
pennie = 0.01
qu = float(input("Inset quarters: "))
di = float(input("Insert dimes: "))
ni = float(input("Insert nickels: "))
pen = float(input("Insert pennies: "))
total_paid = qu * quarter + di * dime + ni * nickel + pen * pennie
return total_paid
def make_drink(drink): # Added this function to consume the resources for the type of drink ordered
if drink == "espresso":
resources['water'] -= 50
resources['coffee'] -= 18
elif drink == "latte":
resources['water'] -= 50
resources['coffee'] -= 18
resources['milk'] -= 150
elif drink == "cappuccino":
resources['water'] -= 250
resources['coffee'] -= 18
resources['milk'] -= 100
else:
print("Not sure what drink was made")
return
def replenish():
resources['water'] = 300
resources['milk'] = 200
resources['coffee'] = 100
return
while True:
print("Welcome to the coffee machine.")
m = "Espresso = $1.50\nLatte = $2.50\nCappuccino = $3.00\n"
selection = ""
print(m)
choice=input("What would you like? (espresso/latte/cappuccino)(e/l/c): ")
# Store the choice in a selection variable to streamline the choice function call
if choice == 'e':
selection = 'espresso'
elif choice == 'l':
selection = 'latte'
elif choice == 'c':
selection = 'cappuccino'
elif choice == 'report':
print("Water:" + str(resources['water']) + "\nMilk:" + str(resources['milk']) + "\nCoffee:" + str(resources['coffee']) + "\nMoney: $" + str(resources['money']))
elif choice == 'replenish':
replenish() # Add a function to replenish resources
elif choice == 'off':
break
if choice in ['c', 'e', 'l']:
chk = check(selection)
print(chk)
if chk == "Enough":
mo=money()
if mo == menu[selection]['cost']:
make_drink(selection)
print('Here is your ', selection)
elif mo > menu[selection]['cost']:
make_drink(selection)
print(f'Here is your ', selection, ', and here is your change $', "{0:.2f}".format(round(mo-menu[selection]["cost"], 2)))
mo = menu[selection]['cost']
elif mo < menu[selection]['cost']:
print(f'Sorry that\'s not enough money. Money refunded.')
mo = 0
resources['money']=mo+resources['money']
print("Money in machine is: $", "{0:.2f}".format(resources['money']))
selection = ""
Forgive me for this being a bit verbose, but following are some of the highlights of this refactored code.
Instead of repeating a lot of the same resource checks and monetary adjustments, an additional variable called "selection" was added to be used for function calls and as an index subscript, which allowed for the streamlining of testing and function calls.
Some of the tests for monetary amounts needed follow up adjustment of the actual money being added to the machine so that the correct money was added, or not added.
Instead of keeping a separate report variable, the contents and functionality of the report value is just embedded within the printing of the report when requested.
In testing the program, I noticed that there was actually no consumption of resources occurring (just testing), so a function was added to consume the resources for the appropriate drink selection.
And just to round out the process, a replenishment option and function was added when resources begin to run out.
Following is some testing output at the terminal when running this program.
#Vera:~/Python_Programs/Coffee$ python3 Coffee.py
Welcome to the coffee machine.
Espresso = $1.50
Latte = $2.50
Cappuccino = $3.00
What would you like? (espresso/latte/cappuccino)(e/l/c): c
Enough
Inset quarters: 12
Insert dimes: 4
Insert nickels: 0
Insert pennies: 0
Here is your cappuccino , and here is your change $ 0.40
Money in machine is: $ 3.00
Welcome to the coffee machine.
Espresso = $1.50
Latte = $2.50
Cappuccino = $3.00
What would you like? (espresso/latte/cappuccino)(e/l/c): report
Water:50
Milk:100
Coffee:82
Money: $3.0
Money in machine is: $ 3.00
Welcome to the coffee machine.
Espresso = $1.50
Latte = $2.50
Cappuccino = $3.00
What would you like? (espresso/latte/cappuccino)(e/l/c):
No doubt, there could be some more polishing of the code, but I believe this heads you in the direction you want to go.
Anyway, give this code a tryout if you desire and see if it helps answer some of your questions and meets the spirit of your project.
Related
i finished this coffee machine simulator but i have a small problem.
How can i remove the line added by the check function after i enter the 'e' or 'l' or 'c'?
Below is the code and a sample of the undesired output and the desired input.
The code:
import os
import time
menu = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee_l": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money":0
}
def money():
quarter=0.25
dime=0.1
nickel=0.05
pennie=0.01
qu=float(input("Inset quarters: "))
di=float(input("Insert dimes: "))
ni=float(input("Insert nickels: "))
pen=float(input("Insert pennies: "))
total_paid=qu*quarter+di*dime+ni*nickel+pen*pennie
return total_paid
def check(drink):
if drink == 'espresso':
if resources['water'] >= 50 and resources['coffee'] >= 18:
return ''
elif resources['water'] <= 50:
return "Sorry there is not enough water."
elif resources['coffee'] <= 18:
return "Sorry there is not enough coffee."
elif drink=='latte':
if resources['water'] >= 200 and resources['milk'] >= 150 and resources['coffee'] >= 24:
return ""
elif resources['water'] < 50:
return "Sorry there is not enough water."
elif resources['coffee'] < 18:
return "Sorry there is not enough coffee."
elif resources['milk'] < 150:
return "Sorry there is not enough milk."
elif drink=='cappuccino':
if resources['water'] >= 250 and resources['milk'] >= 100 and resources['coffee'] >= 24:
return ""
elif resources['water'] < 250:
return "Sorry there is not enough water."
elif resources['coffee'] < 24:
return "Sorry there is not enough coffee."
elif resources['milk'] < 100:
return "Sorry there is not enough milk."
def make_drink(drink):
if drink == "espresso":
resources['water'] -= 50
resources['coffee'] -= 18
resources['money'] += 1.5
elif drink == "latte":
resources['water'] -= 50
resources['coffee'] -= 18
resources['milk'] -= 150
resources['money'] += 2.5
elif drink == "cappuccino":
resources['water'] -= 250
resources['coffee'] -= 18
resources['milk'] -= 100
resources['money'] += 3
else:
print("Not sure what drink was made")
return
def replenish():
resources['water'] += 300
resources['milk'] += 200
resources['coffee'] += 100
return
while True:
print("Welcome to the coffee machine.")
m="Espresso = 1.5$\nLatte = 2.5$\nCappuccino = 3.0$\n"
print(m)
choice=input("What would you like? (espresso/latte/cappuccino)(e/l/c): ")
if choice=='report':
print(f"Water: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}ml\nMoney: {round(resources['money'],2)}$")
elif choice=='replenish':
replenish()
elif choice=='e':
chk=check('espresso')
print(chk)
if chk=='':
mo=money()
if mo == menu['espresso']['cost']:
make_drink('espresso')
print('Here is your coffee')
elif mo > menu['espresso']['cost']:
make_drink('espresso')
print(f'Here is your coffee, and here is your change {round(mo-menu["espresso"]["cost"], 2)} $')
elif mo < menu['espresso']['cost']:
print(f'Sorry that\'s not enough money. Money refunded.')
elif choice=='l':
chk=check('latte')
print(chk)
if chk=='':
mo=money()
if mo == menu['latte']['cost']:
print('Here is your coffee')
elif mo > menu['latte']['cost']:
print(f'Here is your coffee, and here is your change {mo-menu["latte"]["cost"]} $')
resources['money']=mo+resources['money']
elif mo < menu['latte']['cost']:
print(f'Sorry that\'s not enough money. Money refunded.')
elif choice=='c':
chk=check('cappuccino')
print(chk)
if chk=='':
mo=money()
if mo == menu['cappuccino']['cost']:
print('Here is your coffee')
elif mo > menu['cappuccino']['cost']:
print(f'Here is your coffee, and here is your change {mo-menu["cappuccino"]["cost"]} $')
resources['money']=mo+resources['money']
elif mo < menu['cappuccino']['cost']:
print(f'Sorry that\'s not enough money. Money refunded.')
elif choice=='off':
break
time.sleep(3)
os.system('clear')
The undesired output:
Welcome to the coffee machine.
Espresso = 1.5$
Latte = 2.5$
Cappuccino = 3.0$
What would you like? (espresso/latte/cappuccino)(e/l/c): e
Inset quarters:
The desired output:
Welcome to the coffee machine.
Espresso = 1.5$
Latte = 2.5$
Cappuccino = 3.0$
What would you like? (espresso/latte/cappuccino)(e/l/c): e
Inset quarters:
How can I do that without ruining the code?
Thanks
change the line
print(chk)
to
if chk:
print(chk)
The empty line comes from calling check("expresso") and returning an empty line (no failure message to display)
So you only print chk if it has a message, but you don't print it if it's empty.
when check('espresso') exceuted, chk value became empty string. To solve it, you should validate if chk value is not an empty string and then print, else don't do anything. You can change the line :
print(chk)
with this:
print(chk) if chk else ''
So I'm writing a coffee machine code and I'm almost done with it except there is an aspect I don't really know how to fix.
Here is the code:
from data import resources
from data import MENU
penny = 0.01
nickle = 0.05
dime = 0.1
quarter = 0.25
coffee_machine_on = True
espresso_cost = MENU["espresso"]["cost"]
latte_cost = MENU["latte"]["cost"]
cappuccino_cost = MENU["cappuccino"]["cost"]
def resource_deduction():
"""
Deducts the amount of resources each coffee type uses from the coffee machine
"""
if choice == "espresso":
if resources["water"] >= MENU["espresso"]["ingredients"]["water"]:
resources["water"] = resources["water"] - MENU["espresso"]["ingredients"]["water"]
else:
return "Sorry there is no enough water"
if resources["coffee"] >= MENU["espresso"]["ingredients"]["coffee"]:
resources["coffee"] = resources["coffee"] - MENU["espresso"]["ingredients"]["coffee"]
else:
return "Sorry there is no enough coffee"
elif choice == "latte":
if resources["water"] >= MENU["latte"]["ingredients"]["water"]:
resources["water"] = resources["water"] - MENU["latte"]["ingredients"]["water"]
else:
return "Sorry there is no enough water"
if resources["milk"] >= MENU["latte"]["ingredients"]["milk"]:
resources["milk"] = resources["milk"] - MENU["latte"]["ingredients"]["milk"]
else:
return "Sorry there is no enough Milk"
if resources["coffee"] >= MENU["latte"]["ingredients"]["coffee"]:
resources["coffee"] = resources["coffee"] - MENU["latte"]["ingredients"]["coffee"]
else:
return "Sorry there is no enough coffee"
elif choice == "cappuccino":
if resources["water"] >= MENU["cappuccino"]["ingredients"]["water"]:
resources["water"] = resources["water"] - MENU["cappuccino"]["ingredients"]["water"]
else:
return "Sorry there is no enough water"
if resources["milk"] >= MENU["cappuccino"]["ingredients"]["milk"]:
resources["milk"] = resources["milk"] - MENU["cappuccino"]["ingredients"]["milk"]
else:
return "Sorry there is no enough milk"
if resources["coffee"] >= MENU["cappuccino"]["ingredients"]["coffee"]:
resources["coffee"] = resources["coffee"] - MENU["cappuccino"]["ingredients"]["coffee"]
else:
return "Sorry there is no enough coffee"
while coffee_machine_on:
choice = input("What coffee would you like? (espresso/latte/cappuccino): ")
if choice == "espresso":
penny_amnt = int(input("How many pennies?: "))
nickle_amnt = int(input("How many nickles?: "))
dime_amnt = int(input("How many dimes?: "))
quarter_amnt = int(input("How many quarters?: "))
penny_amnt = float(penny_amnt * penny)
nickle_amnt = float(nickle_amnt * nickle)
dime_amnt = float(dime_amnt * dime)
quarter_amnt = float(quarter_amnt * quarter)
total_given = penny_amnt + nickle_amnt + dime_amnt + quarter_amnt
if total_given > espresso_cost:
total_change = total_given - espresso_cost
total_change = round(total_change, 2)
resource_deduction()
if resource_deduction == "Sorry there is no enough water" or resource_deduction == "Sorry there is no enough milk" or resource_deduction == "Sorry there is no enough coffee":
print(resource_deduction)
else:
print(f"Here is ${total_change} in change")
else:
print("Sorry that's not enough money. Money refunded.")
elif choice == "latte":
penny_amnt = int(input("How many pennies?: "))
nickle_amnt = int(input("How many nickles?: "))
dime_amnt = int(input("How many dimes?: "))
quarter_amnt = int(input("How many quarters?: "))
penny_amnt = float(penny_amnt * penny)
nickle_amnt = float(nickle_amnt * nickle)
dime_amnt = float(dime_amnt * dime)
quarter_amnt = float(quarter_amnt * quarter)
total_given = penny_amnt + nickle_amnt + dime_amnt + quarter_amnt
if total_given > latte_cost:
total_change = total_given - latte_cost
total_change = round(total_change, 2)
resource_deduction()
if resource_deduction == "Sorry there is no enough water" or resource_deduction == "Sorry there is no enough milk" or resource_deduction == "Sorry there is no enough coffee":
print(resource_deduction)
else:
print(f"Here is ${total_change} in change")
else:
print("Sorry that's not enough money. Money refunded.")
elif choice == "cappuccino":
penny_amnt = int(input("How many pennies?: "))
nickle_amnt = int(input("How many nickles?: "))
dime_amnt = int(input("How many dimes?: "))
quarter_amnt = int(input("How many quarters?: "))
penny_amnt = float(penny_amnt * penny)
nickle_amnt = float(nickle_amnt * nickle)
dime_amnt = float(dime_amnt * dime)
quarter_amnt = float(quarter_amnt * quarter)
total_given = penny_amnt + nickle_amnt + dime_amnt + quarter_amnt
if total_given > cappuccino_cost:
total_change = total_given - cappuccino_cost
total_change = round(total_change, 2)
resource_deduction()
if resource_deduction == "Sorry there is no enough water" or resource_deduction == "Sorry there is no enough milk" or resource_deduction == "Sorry there is no enough coffee":
print(resource_deduction)
else:
print(f"Here is ${total_change} in change")
else:
print("Sorry that's not enough money. Money refunded.")
elif choice == "report":
print(resources)
elif choice == "off":
coffee_machine_on = False
And here are the MENU and resources dictionaries:
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
When I run the code the resource_deduction dictionary doesn't seem to work properly. The while loop doesn't restart when the coffee machine doesn't contain the right amount of resources. It deducts the resources the first time but keeps running even after the resources are not enough. It's probably some dumb mistake, but I can't seem to find where the code is lacking so I need a fresh pair of eyes to look at the code for me. After the problem is solved the code should work the way I intended it to.
As I understand you should store your resource_deduction function result in a variable and pass choice arg to it :
rd = resource_deduction(choice)
don't forget to add choice in the definition :
def resource_deduction(choice): ...
then compare rd with your strings:
if rd == "Sorry there is no enough water" or rd == "Sorry there is no enough milk" or rd == "Sorry there is no enough coffee"
resource_deduction is a function and you should't compare a function with a string
resource_deduction=="Sorry there is no enough water" #this is always False
I'm building a BMI Calculator in Python and after choosing the metric or imperial system it won't post. The code is 100% functional other than that.
I added the option to choose if you want to use the imperial system or the metric system.
How could I improve the code?
def WeightCalMetric() :
print("BMI-Calculator")
while True:
try:
UserHeight = float(input("What's your height in meters? "))
break
except:
print("Your height has to be a number")
while True:
try:
UserWeight = float(input("What's your weight in Kg? "))
break
except:
print("Your weight has to be a number")
Bmi = UserWeight / (UserHeight ** 2)
FloatBmi = float("{0:.2f}".format(Bmi))
if FloatBmi <= 18.5:
print('Your BMI is', str(FloatBmi),'which means you are underweight.')
elif FloatBmi > 18.5 and FloatBmi < 25:
print('Your BMI is', str(FloatBmi),'which means you are a healthy weight.')
elif FloatBmi > 25 and FloatBmi < 30:
print('your BMI is', str(FloatBmi),'which means you are overweight.')
elif FloatBmi > 30:
print('Your BMI is', str(FloatBmi),'which means you are obese.')
def WeightCalImperial() :
print("BMI-Calculator")
while True:
try:
UserHeight = float(input("What's your height in inches? "))
break
except:
print("Your height has to be a number")
while True:
try:
UserWeight = float(input("What's your weight in Lbs? "))
break
except:
print("Your weight has to be a number")
Bmi = 703 * (UserWeight / (UserHeight ** 2))
FloatBmi = float("{0:.2f}".format(Bmi))
if FloatBmi <= 18.5:
print('Your BMI is', str(FloatBmi),'which means you are underweight.')
elif FloatBmi > 18.5 and FloatBmi < 25:
print('Your BMI is', str(FloatBmi),'which means you are a healthy weight.')
elif FloatBmi > 25 and FloatBmi < 30:
print('your BMI is', str(FloatBmi),'which means you are overweight.')
elif FloatBmi > 30:
print('Your BMI is', str(FloatBmi),'which means you are obese.')
print("Hi welcome to this BMI Calculator")
print("First choose if you want to use the metric system or the imperial system")
print('Write "Metric" for the metric system or write "Imperial" for the imperial system')
KgOrLbs = None
while KgOrLbs not in ("metric", "Metric", "imperial", "Imperial"):
KgOrLbs = input("Metric or Imperial? ")
if KgOrLbs == "metric, Metric":
WeightCalMetric()
elif KgOrLbs == "imperial" "Imperial":
WeightCalImperial()
I'm supposed to add more details, but I don't really have any more details, to be honest, so now I'm just writing all of this just so I can post this
You should change the while loop where you check the inputs. The code below lowercases the input and checks whether it is "metric" or "imperial", so there is no need to check for capitalized parameters
KgOrLbs = input("Metric or Imperial? ")
while KgOrLbs.lower() not in ["metric", "imperial"]:
KgOrLbs = input("Metric or Imperial? ")
if KgOrLbs.lower() == "metric":
WeightCalMetric()
elif KgOrLbs.lower() == "imperial":
WeightCalImperial()
money = 0
day = 1
items = []
def gameplay():
global items
global money
global day
energy = 10
work = 0
while True:
print("Type 'help' for assistance")
play = str(input("-> ")).strip()
if play.lower() == "help":
print("""
Type : To : Cost:
'Work' Get Money (only once then next day) 5 Energy
'Mall' Buy Stuff 5 Energy
'Items' Check Inventory N/A
'Money' Check Balance Of Money N/A
'Energy' Check Balance Of Energy N/A
'Day' Check your day, day 1 , day 2 etc. N/A
'Done' End Your Day N/A """)
elif play.lower() == "work":
if work == 1:
print("You have already worked!")
else:
energy -= 5
print("Working......")
money += 5
work += 1
print("You now have $%s and %s Energy" % (money, energy))
elif play.lower() == "mall":
energy -= 5
while True:
print("What do you want to do?")
print("""
Type : To: Cost:
Coffee Buy Normal Coffee : +2 energy next day $4
Lottery Buy A Lottery Ticket (per day) $10
Money Check Balance Of Money N/A
Energy Check Balance Of Energy N/A
Items Check Your Inventory N/A
Exit Exit the shopping mall N/A
""")
mall = input("-> ").strip()
if mall.lower() == "coffee":
if "coffee" in list:
print("You have already bought a cup of coffee!")
elif money < 4:
print("You don't have enough money!")
else:
print("You bought a coffee")
items.append("coffee")
print(items)
if mall.lower() == "lottery":
if "Lottery Ticket" in list:
print("You have already bought a ticket! Try again next day!")
lot = random.randint(1, 20)
jack = random.randint(100, 1000)
while True:
if money < 10:
print("You don't have enough money!")
break
else:
list.append("Lottery Ticket")
money -= 10
print("Choose a number between 1 to 20")
try:
lotg = int(input("-> "))
if lotg == lot:
print("Congratulations you have won $%s" % (jack))
money += jack
break
elif lotg != lot:
print("Sorry but you lost! Good luck Next Time")
break
except ValueError:
print("Please Type A Number")
elif mall.lower() == "money":
print("You currently have $%s" % (money))
elif mall.lower() == "energy":
print("You currently have %s" % (energy))
elif mall.lower() == "items":
print("These are your following items:")
print(items)
elif mall.lower() == "exit":
print("Exiting mall......")
break
elif play.lower() == "items":
print("These are your following items:")
print(items)
elif play.lower() == "money":
print("You currently have $%s" % (money))
elif play.lower() == "energy":
print("You currently have %s" % (energy))
elif play.lower() == "day" :
print("Its Day %s " % (day))
elif play.lower() == "done":
while True:
print("Are You Sure?")
sure = str(input("-> "))
if sure.lower() not in ["yes","no"]:
print("Please Type Yes Or No ")
elif sure.lower() == "yes":
print("Going Home For Next Day........")
home()
elif sure.lower() == "no":
print("Okay!")
break
def noenergy():
print("You don't have enough energy to do that")
def home():
print("You are at home..")
gameplay()
It sometimes shows:
Traceback (most recent call last):
File "/home/alex/.config/JetBrains/PyCharm2020.1/scratches/scratch_718.py", line 120, in <module>
gameplay()
File "/home/alex/.config/JetBrains/PyCharm2020.1/scratches/scratch_718.py", line 50, in gameplay
if "coffee" in list:
TypeError: argument of type 'type' is not iterable
when i test it in this order
input -> mall
input -> coffee
The error message should pop up
Tried to change the while loop part to a for loop but , still the same and I can't find any answers on a single website
Why is this happening? The loop? The list? The input?
list is not a variable containing a list, it's the type (hence the error message) of list objects.
It looks like you meant to use the variable items which is a list and forgot or got confused.
I'm trying to write the Camel game using functions instead of so many nested if statements. I think I've done something wrong though, I've had to tinker with the native distance portion a lot as I kept getting into parts where they only got further away not closer. But now after trying to change the randomint values I can never escape them. Any suggestions for improvement are much appreciated!
Here is my code:
import random
def quitGame():
print("I am guitting now.")
return True
def status(milesTraveled, thirst, camelTiredness, distanceNativesTraveled, drinks):
print(
"""
You have traveled %d miles
Your Camel Status is %d (lower is better)
You have %d drinks left in your canteen
Your thirst is %d (lower is better)
The Natives are %d miles behind you
"""%(milesTraveled,camelTiredness,drinks,thirst,distanceNativesTraveled))
def rest():
print("The camel is happy")
distanceN = random.randint(7,14)
return(distanceN)
def fullSpeed():
distanceT = random.randint(10,20)
print("You travel %d miles"%distanceT)
camelT = random.randint(1,3)
distanceN = random.randint(7,14)
return(distanceT,camelT,distanceN)
def moderateSpeed():
distanceB = random.randint(5,12)
print("You travel %d miles"%distanceB)
nativesB = random.randint(7,14)
return(distanceB,nativesB)
def thirsty(drinksLeft):
drinksL = drinksLeft - 1
return(drinksL)
def main():
choice = ""
done = False # loop variable
#variables for game
milesTraveled = 0
thirst = 0
camelTiredness = 0
distanceNativesTraveled = -20
drinks = 5
print(
"""
Welcome to the Camel Game!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down. Survive your
desert trek and out run the native.
"""
)
while not done:
findOasis = random.randint(1,20)
print(
"""
Here are your choices:
A - Drink from you canteen.
B - Ahead moderate speed.
C - Ahead full speed.
D - Stop and rest for night.
E - Status check.
Q - Quit the Game
"""
)
choice = input(" Your choice?\n")
if choice.upper() == "Q":
done = quitGame()
elif findOasis is 1 :
print("Wow! You've found an Oasis. Your thirst is quenched, canteen topped off, \
and your camel is now well rested and happy.")
drinks = 5
thirst = 0
camelTiredness = 0
elif choice.upper() == "A":
if drinks > 0:
drinks = thirsty(drinks)
thirst = 0
else:
print("Error: Uh oh! No water left.")
elif choice.upper() == "B":
milesB,nativesB = moderateSpeed()
milesTraveled += milesB
camelTiredness += 1
thirst += 1
distanceNativesTraveled += nativesB
elif choice.upper() == "C":
milesT,camelTired,nativesT= fullSpeed()
milesTraveled += milesT
camelTiredness += camelTired
distanceNativesTraveled += nativesT
thirst += 1
elif choice.upper() == "D":
distanceT = rest()
camelTiredness = 0
distanceNativesTraveled += distanceT
elif choice.upper() == "E":
statusCheck = status(milesTraveled, thirst, camelTiredness, distanceNativesTraveled, drinks)
else:
print("That was not a correct choice - Enter (A through E or Q)")
if thirst > 4 and thirst <= 6:
print("You are thirsty")
elif thirst > 6:
print("GAME OVER \nYou died of thirst!")
done = True
elif camelTiredness > 5 and camelTiredness <= 8:
print("Your camel is getting tired")
elif camelTiredness > 8:
print("GAME OVER \nYour camel is dead.")
done = True
elif distanceNativesTraveled >= 0:
print("GAME OVER \nThe natives have captured you!")
done = True
elif distanceNativesTraveled > -15:
print("The natives are getting close!")
elif milesTraveled >= 200:
print("YOU WIN \nCongrats, you made it across the desert!")
done = True
# call main
main()
The game ends when distanceNativesTraveled >= 0 and yet there's no code at all to decrease distanceNativesTraveled. So with every turn distanceNativesTraveled keeping increasing, the game is bound to end quickly.
What you really want here is to check if distanceNativesTraveled has surpassed milesTraveled, so change:
elif distanceNativesTraveled >= 0:
to:
elif distanceNativesTraveled >= milesTraveled:
And for the check to see if natives are getting close, change:
elif distanceNativesTraveled > -15:
to:
elif distanceNativesTraveled - milesTraveled > -15:
And to properly show the how many miles the natives are behind you, you should show the difference between the miles you and the natives traveled, so change:
"""%(milesTraveled,camelTiredness,drinks,thirst,distanceNativesTraveled))
to:
"""%(milesTraveled,camelTiredness,drinks,thirst,milesTraveled - distanceNativesTraveled))