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
Related
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.
How can I end a function when a user types a specific keyword (e.g. 'off') in an input without having to add the necessary code within each input? Basically I want the function to completely stop when a user types the word 'off' anywhere in any of the inputs below. I have created a function (see bottom of code) and have tried placing/calling it throughout my code but am not sure exactly where to put it or if I can even do this with a function? If not, how can I achieve this?
def order_coffee():
drink = input("What would you like? (espresso/latte/cappuccino): ")
user_owes = int(0)
if drink == "espresso":
user_owes = round(1.5, 2)
elif drink == "latte":
user_owes = round(2.5, 2)
elif drink == "cappuccino":
user_owes = round(3.0, 2)
print(f"Please insert coins, you owe ${user_owes}.")
quarters = (int(input("How many quarters?: ")) * .25)
dimes = (int(input("How many dimes?: ")) * .1)
nickels = (int(input("How many nickels?: ")) * .05)
pennies = (int(input("How many pennies?: ")) * .01)
user_paid = round(quarters + dimes + nickels + pennies, 2)
print(f"You have inserted ${user_paid}.")
change = round(user_paid - user_owes, 2)
if user_paid >= user_owes:
print(f"Here is ${change} in change.")
print(f"Here is your {drink} ☕. Enjoy!")
order_coffee()
else:
print("Sorry that's not enough money. Money refunded.")
order_coffee()
order_coffee()
def off():
if input == "off":
return
Create your own input function an add the desired behaviour:
def my_input(*args, **kwargs):
str = input(*args, **kwargs)
if str == "off":
exit()
return str
This will exit from the entire application when the user input is "off", to exit only from the function throw an exception instead, and catch it outside the function call. For instance:
def my_input(*args, **kwargs):
str = input(*args, **kwargs)
if str == "off":
raise ValueError('Time to go')
and:
def order_coffee():
try:
# your code
except ValueError as err:
# handle it accordingly
return
A clearer approach is to create, throw, and handle a custom Exception. Have a look at this SO Thread to get an idea of how to implement those custom exceptions.
def order_coffee():
drink = input("What would you like? (espresso/latte/cappuccino): ")
user_owes = int(0)
if drink == "espresso":
user_owes = round(1.5, 2)
elif drink == "latte":
user_owes = round(2.5, 2)
elif drink == "cappuccino":
user_owes = round(3.0, 2)
elif drink == 'off':
return None
print(f"Please insert coins, you owe ${user_owes}.")
quarters = (int(input("How many quarters?: ")) * .25)
dimes = (int(input("How many dimes?: ")) * .1)
nickels = (int(input("How many nickels?: ")) * .05)
pennies = (int(input("How many pennies?: ")) * .01)
user_paid = round(quarters + dimes + nickels + pennies, 2)
print(f"You have inserted ${user_paid}.")
change = round(user_paid - user_owes, 2)
if user_paid >= user_owes:
print(f"Here is ${change} in change.")
print(f"Here is your {drink} ☕. Enjoy!")
order_coffee()
else:
print("Sorry that's not enough money. Money refunded.")
order_coffee()
order_coffee()
You can create your own input function to check for this and when the event 'off' is entered then exit the program. That way if someone enters "off" at any point in the program it will end.
import sys
def get_input(text):
user_feedback = input(text)
if user_feedback == 'off':
sys.exit()
return user_feedback
def order_coffee():
print("Welcome to the coffee robot! (type 'off' to exit at any time)")
drink = get_input("What would you like? (espresso/latte/cappuccino): ")
user_owes = int(0)
if drink == "espresso":
user_owes = round(1.5, 2)
elif drink == "latte":
user_owes = round(2.5, 2)
elif drink == "cappuccino":
user_owes = round(3.0, 2)
print(f"Please insert coins, you owe ${user_owes}.")
quarters = (int(get_input("How many quarters?: ")) * .25)
dimes = (int(get_input("How many dimes?: ")) * .1)
nickels = (int(get_input("How many nickels?: ")) * .05)
pennies = (int(get_input("How many pennies?: ")) * .01)
user_paid = round(quarters + dimes + nickels + pennies, 2)
print(f"You have inserted ${user_paid}.")
change = round(user_paid - user_owes, 2)
if user_paid >= user_owes:
print(f"Here is ${change} in change.")
print(f"Here is your {drink} ☕. Enjoy!")
order_coffee()
else:
print("Sorry that's not enough money. Money refunded.")
order_coffee()
order_coffee()
I'm sure you have all heard of the GCSE fruit machine challenge. Well I am having issues with that, you see, when the user spins 3 skulls it doesn't deduct all their credits and when they only spin 2 skulls it doesn't deduct 1 credit. If anyone can help please do.
credit = 1
import time
t = 1
while True:
import random
symbols = 'Star' , 'Skull'
spin = random.choices(symbols,k=1)
spin2 = random.choices(symbols,k=1)
spin3 = random.choices(symbols,k=1)
ask = input('do you want to spin? ')
if ask == 'yes':
credit = (credit - 0.2)
credit = (round(credit, 2))
print('You now have... ' +str(credit) + ' credit(s).')
time.sleep (t)
print('** NOW ROLLING **')
time.sleep (t)
print('You rolled... ' +str(spin) +str(spin2) +str(spin3))
time.sleep (t)
if (spin == spin2 == 'Skull' or spin == spin3 == 'Skull' or spin2 == spin3 == 'Skull'):
credit = (credit - 1)
credit = (round(credit, 2))
print('Uh Oh! you rolled 2 skulls.... you lost 1 credit sorry!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif spin == 'Skull' and spin2 == 'Skull' and spin3 == 'Skull':
credit = (credit - credit)
print('You rolled 3 Skulls!! You lost all your credits!')
break
elif spin == spin2 and spin2 == spin3:
credit = (credit + 1)
print('You won 1 credit!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif spin == spin2 or spin == spin3 or spin2 == spin3:
credit = (credit + 0.5)
credit = (round(credit, 2))
print('You won 0.5 credits!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
else:
print('Sorry you didnt win anything.')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif ask == 'no':
print('Your total winnings are.... ' +str(credit))
break
else:
print('please say yes or no..')
continue
The problem is you are comparing list to string where "Skull" is a string and the variable "spin" is a list of one element. To solve this you can turn "spin" to a string using spin = random.choice(symbols) which will make one choice as a string.
You seem new to python so I also rewrote your code. You are more than welcome to ask questions about it :)
import time
import random
t = 1
credit = 1.0
while True:
symbols = "Star", "Skull"
spins = random.choices(symbols, k=3)
ask = input("Do you want to spin? ")
if ask == "yes":
credit -= 0.2
print(f"You now have... {credit} credit(s).")
time.sleep(t)
print("** NOW ROLLING **")
time.sleep(t)
print("You rolled... " + " ".join(spins))
time.sleep(t)
if sum(spin == "Skull" for spin in spins) == 2:
credit -= 1
print("Uh Oh! you rolled 2 skulls.... you lost 1 credit, sorry!")
elif sum([spin == "Skull" for spin in spins]) == 3:
credit = 0
print("You rolled 3 Skulls!! You lost all your credits!")
elif all(spin == spins[0] for spin in spins):
credit += 1
print("You won 1 credit!")
elif len(set(spins)) != len(spins):
credit += 0.5
print("You won 0.5 credits!")
else:
print("Sorry you didn't win anything.")
credit = (round(credit, 2))
print(f"You now have a total balance of... {credit} credits!")
if credit >= 0.2:
continue
else:
print("Sorry! You don't have enough credits.")
break
elif ask == "no":
print(f"Your total winnings are.... {credit}")
break
else:
print("Please say yes or no..")
continue
Good Luck
My For loops don't seem to be "activating" or working. I am writing a program about the Oregon trail and I am working on the "shop" part. Here is what its been doing,
First it was asking the same question "How much food would you like to buy" until I pressed E to break out of it. Now its not doing the math or activating the for loop. Here is the code i'm working with:
import random
global all
global PlayerPerk
#Organ Trail Start--
print("You may:")
print("1. Travel the road")
print("2. Learn More about the road")
choiceStart = input("What is your choice? ")
def Shop(PlayerPerk, money):
global all
#intro
print("Before You set off on your Journey, you will need some supplies to survive the dangerous trail. You will need Food, Ammo, Spare Parts, Clothing, and Oxen")
#money define
if PlayerPerk == "1":
print("You are A cop. You have $400 to spend.")
money = 400
elif PlayerPerk == "2":
print("You are a Clerk. You have $700 to spend.")
money = 700
elif PlayerPerk == "3":
print("You are a Banker. You have $1600 to spend.")
money =1600
print("Welcome to My shop! First thing, how much Food would you like to buy?")
#Food -------------------------------------------------------------------------------
FoodToBuy = input("How Much food would you like (each cost $2):")
MoneySubtract = FoodToBuy*2
for i in range(1,1000):
if FoodToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent: ",MoneySubtract, "You now have: ",money)
Food = FoodToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif FoodToBuy == "e":
break
#Ammo --------------------------------------------------------------------------------
print("Now lets buy some Ammo!")
AmmoToBuy = input("How Much Rifle Ammo would you like to buy (each box cost $5):")
MoneySubtract = AmmoToBuy*5
for i in range(1,1000):
if AmmoToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:",MoneySubtract, "You now have: ",money)
Ammo = AmmoToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
#Spare Parts---------------------------------------------------------------------------
print("Now lets buy some Spare Parts!")
SparePartsToBuy = input("How much Spare Parts would you like to buy (each costs $20 [max of 9]):")
MoneySubtract = SparePartsToBuy*20
for i in range(1,1000):
if SparePartsToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = SparePartsToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
#chlothing-----------------------------------------------------------------------------
print("Now, you need to buy some chlothes!")
ClothesToBuy = input("How many Clothes would you like to buy (each pair costs $5):")
MoneySubtract = ClothesToBuy*5
for i in range(1,1000):
if ClothesToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = ClothesToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
#oxen-------------------------------------------------------------------------------------
print("Finally, you need to buy some Ox!")
OxenToBuy = input("How many Oxen would you like to buy (each costs $30):")
MoneySubtract = OxenToBuy*30
for i in range(1,1000):
if OxenToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = OxenToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
if AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
#----------------------------------------------------------------------------------------------
def MonthStart(PlayerPerk):
global all
print("It is 1848. Your jumping off place for oregon is Independence, Missouri. You must decide which month to leave Indepence.")
print("1. March")
print("2. April")
print("3. May")
print("4. June")
print("5. July")
print("6. ask for advice")
StartingMonth = input("What is your choice? ")
if StartingMonth == ("6"):
global all
print("You attend a public meeting held for 'folks with the California - Oregon fever.' You're told:")
print("If you leave too early, there won't be any grass for your oxen to eat.")
print("if you leave to late, you may not get to Oregon before winter comes.")
print("If you leave at just the write time, there will be green grass and the weather will still be cool.")
exMonthChoice = input("Would you like to stop viewing?(y/n) ")
if exMonthChoice ==("Y" or "y"):
MonthStart(PlayerPerk)
elif exMonthChoice == ("N"or"n"):
print("Still viewing")
else:
print("Unknown usage.")
elif StartingMonth == ("1"):
Month = "March"
print("You chose: ", Month )
Shop(PlayerPerk,0)
elif StartingMonth == ("2"):
Month = "April"
print("You chose: ", Month )
Shop(PlayerPerk,0)
elif StartingMonth == ("3"):
Month = "May"
print("You chose: ", Month )
Shop(PlayerPerk,0)
elif StartingMonth == ("4"):
Month = "June"
print("You chose: ", Month)
Shop(PlayerPerk,0)
elif StartingMonth == ("5"):
Month = "July"
print("You chose: ", Month)
Shop(PlayerPerk,0)
global all
############################
#NAMING
def NAMING(PlayerPerk):
global all
print("Now lets name your person")
Name1 = input("What is the name of the Wagon leader ")
Name2 = input("What is the name of the 2nd person in the family? ")
Name3 = input("What is the name of the 3rd person in the family? ")
Name4 = input("What is the name of the 4th person in the family? ")
Name5 = input("What is the name of the 5th person in the family? ")
NameVerification = input("Are these names correct?")
if NameVerification == ("Y" or "y"):
MonthStart(PlayerPerk)
elif NameVerification ==("N" or "n"):
NAMING(PlayerPerk)
#Start OCCUPATION
def Occupation():
global all
############################################################
print("Many people find themselves on the road. You may : ")
print("1. Be a cop from Kentucky.")
print("2. Be a clerk from Jersey City.")
print("3. Be a Banker from Boston.")
print("4. Find out the differences between these choices.")
############################################################
jobChoice = input("What is your choice? ")
if jobChoice == ("4"):
print("Traveling to Oregon isn't easy! But if you are a banker, you'll have more money for supplies and services than a cop or a clerk.")
print(" But, a cop has a higher chance of haveing a successful hunt!")
print("And a Clerk has a higher survival rate!")
exChoice1 = input("Would you like to stop viewing your options?(y/n) ")
if exChoice1 == ("y" or "Y"):
Occupation()
###############################
elif jobChoice ==("1"):
print("You chose to be a cop from Kentucky!")
PlayerPerk = ("1")
NAMING(PlayerPerk)
elif jobChoice == ("2"):
print("You chose to be a clerk from Jersey City!")
PlayerPerk = ("2")
NAMING(PlayerPerk)
elif jobChoice == ("3"):
print("You chose to be a Banker from Boston!")
PlayerPerk = ("3")
NAMING(PlayerPerk)
#Call choices
if choiceStart == ("1"):
Occupation()
And here is the specific code I'm having troubles with:
def Shop(PlayerPerk, money):
global all
#intro
print("Before You set off on your Journey, you will need some supplies to survive the dangerous trail. You will need Food, Ammo, Spare Parts, Clothing, and Oxen")
#money define
if PlayerPerk == "1":
print("You are A cop. You have $400 to spend.")
money = 400
elif PlayerPerk == "2":
print("You are a Clerk. You have $700 to spend.")
money = 700
elif PlayerPerk == "3":
print("You are a Banker. You have $1600 to spend.")
money =1600
print("Welcome to My shop! First thing, how much Food would you like to buy?")
#Food -------------------------------------------------------------------------------
FoodToBuy = input("How Much food would you like (each cost $2):")
MoneySubtract = FoodToBuy*2
for i in range(1,1000):
if FoodToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent: ",MoneySubtract, "You now have: ",money)
Food = FoodToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif FoodToBuy == "e":
break
#Ammo --------------------------------------------------------------------------------
print("Now lets buy some Ammo!")
AmmoToBuy = input("How Much Rifle Ammo would you like to buy (each box cost $5):")
MoneySubtract = AmmoToBuy*5
for i in range(1,1000):
if AmmoToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:",MoneySubtract, "You now have: ",money)
Ammo = AmmoToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
#Spare Parts---------------------------------------------------------------------------
print("Now lets buy some Spare Parts!")
SparePartsToBuy = input("How much Spare Parts would you like to buy (each costs $20 [max of 9]):")
MoneySubtract = SparePartsToBuy*20
for i in range(1,1000):
if SparePartsToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = SparePartsToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
#chlothing-----------------------------------------------------------------------------
print("Now, you need to buy some chlothes!")
ClothesToBuy = input("How many Clothes would you like to buy (each pair costs $5):")
MoneySubtract = ClothesToBuy*5
for i in range(1,1000):
if ClothesToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = ClothesToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
elif AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
#oxen-------------------------------------------------------------------------------------
print("Finally, you need to buy some Ox!")
OxenToBuy = input("How many Oxen would you like to buy (each costs $30):")
MoneySubtract = OxenToBuy*30
for i in range(1,1000):
if OxenToBuy == int:
if money - MoneySubtract > 0:
money -= MoneySubtract
print("You spent:", MoneySubtract, "You now have: ",money)
SpareParts = OxenToBuy
MoneySubtract = 0
else:
print("Insufficent Funds!")
Shop(PlayerPerk,money)
if AmmoToBuy=="e":
break
else:
print("Unknown input!")
Shop(PlayerPerk, 0)
The only problem i'm having is making the for loops work. I plan on using all the variables as the code develops. If you know whats wrong or have any information on anything let me know! Thank you in advance!
I wrote this code because I'm just starting out and wanted to practice a little bit. This code only works 1 out of every 10 times I try to run it. I wrote it in Jupyter Notebook.
When it doesn't work I get the NameError: name 'oatcalories' is not defined. Sometimes it says 'eggcalories' is not defined as well.
How do I make sure it works 100% of the time?
Here it is:
while True:
one = input("What are you eating for breakfast? (Enter one item at a time and 'done' when done)\n")
if one == "done":
print ("Done")
break
if one.lower() == "eggs":
quantegg = input("How many eggs? ")
eggcalories = (int(quantegg) * 78)
elif one.lower() == "oatmeal":
quantoat = input("How many servings of oatmeal? ")
oatcalories = (int(quantoat) * 120)
elif one.lower() == "avacado":
quantav = input("How many avacados: ")
avcalories = (int(quantav) * 120)
elif one.lower() == "toast":
quantoast = input("How many pieces of toast?: ")
toastcalories = (int(quantoast) * 70)
butter = input("Did you add butter?")
if butter.lower()[0] == "y":
quantbut = input("How many servings of butter?: ")
butcalories = (int(quantbut) * 102)
elif butter.lower()[0] == "n":
butcalories = (int(quantbut) * 0)
else:
pass
break_total = eggcalories + oatcalories + avcalories + toastcalories + butcalories
print ("Total calories for breakfast:",break_total)
This newbie appreciates your help!
You aren't defining any of the variables used in the break_total line at the very bottom. If your code was like this, it should work fine:
eggcalories = 0
oatcalories = 0
avcalories = 0
toastcalories = 0
butcalories = 0
while True:
one = input("What are you eating for breakfast? (Enter one item at a time and 'done' when done)\n")
if one == "done":
print ("Done")
break
if one.lower() == "eggs":
quantegg = input("How many eggs? ")
eggcalories = (int(quantegg) * 78)
elif one.lower() == "oatmeal":
quantoat = input("How many servings of oatmeal? ")
oatcalories = (int(quantoat) * 120)
elif one.lower() == "avacado":
quantav = input("How many avacados: ")
avcalories = (int(quantav) * 120)
elif one.lower() == "toast":
quantoast = input("How many pieces of toast?: ")
toastcalories = (int(quantoast) * 70)
butter = input("Did you add butter?")
if butter.lower()[0] == "y":
quantbut = input("How many servings of butter?: ")
butcalories = (int(quantbut) * 102)
elif butter.lower()[0] == "n":
butcalories = (int(quantbut) * 0)
else:
pass
break_total = eggcalories + oatcalories + avcalories + toastcalories + butcalories
print ("Total calories for breakfast:",break_total)
The cause for error was because you were trying to add things that you hadn't set yet, so when you tried to add them the interpreter didn't know what you were referencing.