The program allows the user to enter money and select an item that outputs the price.
Towards the end, the if statements, if purchase_choice == 1: print("************ The item costs $1.00 ************") and the following statements after that one, is not printing in the output. Can someone help me?
Here's the code.
print("*********************************")
print("Welcome to Vending Machine Bravo!")
print("*********************************")
print("If you would like to make a selection, please insert the appropriate currency into the machine.")
Currency deposit
num_5Dollars = 5.00
num_Dollars = 1.00
num_Quarters = .25
num_Dimes = .10
num_Nickels = .05
num_Pennies = .01
print()
print("Please enter:")
if num_5Dollars == 5.00:
print("5.00 for $5 bills")
if num_Dollars == 1.00:
print("1.00 for $1 bills")
if num_Quarters == .25:
print(".25 for Quarters")
if num_Dimes == .10:
print(".10 for dimes")
if num_Nickels == .05:
print(".05 for nickels")
if num_Pennies == .01:
print(".01 for pennies")
user_val = float(input())
if int(user_val) == 0:
print("0 to cancel")
print("At any point if you wish to cancel operation or go back to last menu, please enter 0. Thank you!:")
print()
print(int(user_val))
print()
print("************ Total money in machine is: ", user_val , "************")
purchase item selection
Skittles = {'type' '1''Price': 1.00}
Reeses = {'type' '2' 'Price': 1.19}
M_and_M = {'type' '3' 'Price': 1.50}
Chex_Mix = {'type' '4' 'Price': 0.99}
Honey_Bun = {'type' '5' 'Price': 1.99}
types = [Skittles, Reeses, M_and_M, Chex_Mix, Honey_Bun]
global type
type = [Skittles, Reeses, M_and_M, Chex_Mix, Honey_Bun]
print()
print("At any point if you wish to cancel operation or go back to last menu, please enter 0. Thank you!:")
print()
print("If you would like to purchase:")
print()
print("Skittles - type '1', (Price = $1.00)")
print("Reeses - type '2', (Price = 1.19)")
print("M_and_M - type '3', (Price = $1.50)")
print("Chex_Mix - type '4', (Price = $0.99)")
print("Honey_Bun - type '5', (Price = $1.99)")
print()
purchase_choice = input()
print("Your enter is:", purchase_choice)
if user_val == 0:
print('Item selection stopped')
else:
if purchase_choice == 1:
print("************ The item costs $1.00 ************")
if purchase_choice == 2:
print("************ The item costs $1.19 ************")
if purchase_choice == 3:
print("************ The item costs $1.50 ************") [tag:tag-name]
if purchase_choice == 4:
print("************ The item costs $0.99 ************")
if purchase_choice == 5:
print("************ The item costs $1.99 ************")
You need to convert the user input string to an integer.
purchase_choice = int(input())
Related
I'm creating a vending machine program that simulates the action through a loop that ends when the user enters 0 but it doesn't print "0 to cancel" in the output. I tried putting it at the top before the if statements but, I want to be able to enter an input after the if statements are printed. So how could I fix that?
It says that user_val is undefined when I equal it to 0 but I did define it at the bottom.
If someone could help please!
print("*********************************")
print("Welcome to Vending Machine Bravo!")
print("*********************************")
print("If you would like to make a selection, please insert the appropriate currency into the machine.")
# Currency deposit [tag:tag-name]
num_5Dollars = 5.00
num_Dollars = 1.00
num_Quarters = .25
num_Dimes = .10
num_Nickels = .05
num_Pennies = .01
currency = [num_5Dollars, num_Dollars, num_Quarters, num_Dimes, num_Nickels, num_Pennies]
if num_5Dollars == 5.00:
print("5.00 for $5 bills")
if num_Dollars == 1.00:
print("1.00 for $1 bills")
if num_Quarters == .25:
print(".25 for Quarters")
if num_Dimes == .10:
print(".10 for dimes")
if num_Nickels == .05:
print(".05 for nickels")
if num_Pennies == .01:
print(".01 for pennies")
if int(float(user_val)) == 0:
print("0 to cancel")
user_val = float(input())
Your user_val defined under the line if int(float(user_val)) == 0.
And if you want to say to user 0 to cancel, you don't need to check int(float(user_val)) == 0, because while this doesn't happened, it won't print this instruction.
So basically, you need to remove if int(float(user_val)) == 0: line
I have a task where I'm supposed to create a ticket where the user first choose which kind of ticket they want and then if they want to add a bag (option 1) or a meal (option 2). The user can also choose to remove a bag (option 3) or a meal (option 4), if they regret their first choice. All the choices are then gonna be printed on a receipt.
My problem is how to store the option that the user choses. I created a while loop that runs until the user want to finalize its ticket. This is my while-loop:
while yourchoice != 5:
if yourchoice == 1:
addonebag = str('1 bag(s) registered')
choiceslist.append(addonebag)
elif yourchoice == 2:
addonemeal = str('1 meal(s) registered')
choiceslist.append(addonemeal)
elif yourchoice == 3:
removebag = str('0 bag(s) registered')
choiceslist.pop(addonebag)
choiceslist.append(removebag)
elif yourchoice == 4:
removemeal = str('0 meal(s) registered')
choiceslist.pop(1,addmeal)
choiceslist.insert(1,removemeal)
else:
print('\n'
'Invalid option. Please try again.')
I want the output to look like this depending on the option the user chose (it can also say 1 bag or 1 meal or both):
Currently you have:
0 bag(s) registered
0 meal(s) registered
The problem is that when I create this list the output is if I chose option 1 in the first loop: ['1 bag(s) registered']
If I then chose option 3 in the next loop, the output is: ['1 bag(s) registered' '0 bag(s) registered'] instead of just ['0 bag(s) registered'].
I've tried to use pop and insert on specific indexes but it doesn't work. Does anyone have any idea of how I can solve this? Thanks!
You can try this, if this works for you.
As you only needs to get the current choice. I don't think you need to
append into the list. You can store the choices for meal and bag separately and in the end you can create a new list by using both choices.
# In the beginning choices should be 0
bag_choice = '0 bag(s) registered'
meal_choice = '0 meal(s) registered'
while yourchoice != 5:
if yourchoice == 1:
bag_choice = '1 bag(s) registered'
elif yourchoice == 2:
bag_choice = '1 meal(s) registered'
elif yourchoice == 3:
bag_choice = '0 bag(s) registered'
elif yourchoice == 4:
meal_choice = '0 meal(s) registered'
else:
print('\n'
'Invalid option. Please try again.')
#creating a list from bag_choice and meal_choice
choice_list = [bag_choice, meal_choice]
print(choice_list)
Thank you for your help! I actually tried another method where I put bag to 1 or 0 depending on the choice and it works!
Now my code looks like this:
def tickettype():
print('Ticket types: \n'
'1. Budget: 500 kr \n'
'2. Economy: 750 kr \n'
'3. VIP: 2000 kr \n')
def options():
print('\nHere are your options: \n'
'1. Add bag (max 1) \n'
'2. Add meal (max 1) \n'
'3. Remove bag \n'
'4. Remove meal \n'
'5. Finalize ticket \n')
tickettype()
tickettype1 = int(input('Choose your ticket type: '))
if tickettype1 == 1:
ticket = 500
elif tickettype1 == 2:
ticket = 750
elif tickettype1 == 3:
ticket = 2000
options()
print('\n'
'Currently you have: \n'
'0 bag(s) registered \n'
'0 meal(s) registered \n')
yourchoice = int(input('Your choice: '))
bag = 0
meal = 0
addbag = 0
addmeal = 0
while yourchoice != 5:
if yourchoice == 1:
bag = 1
bagprice = 200
addbag = str('Bag : 200')
elif yourchoice == 2:
meal = 1
mealprice = 150
addmeal = str('Meal : 150')
elif yourchoice == 3:
bag = 0
elif yourchoice == 4:
meal = 0
else:
print('\n'
'Invalid option. Please try again.')
print('\n'
f'Currently you have: \n{bag} bag(s) registered \n{meal} meal(s) registered')
options()
yourchoice = int(input('Your choice: '))
# When the user press 5:
#EDITED AFTER THIS LINE
#print(f'\nReceipt:\nTicket : {ticket}\n{addbag}\n{addmeal} \nTotal: {ticket+bagprice+mealprice}'
#create a new variable to store Total price, adding mealprice or bagprice only if they are selected else 0 will be added
Total = (mealprice if meal == 1 else 0) + (bagprice if bag == 1 else 0) + ticket
print(f'\nReceipt:\nTicket:{ticket}')
#print bag only if it is selected, bag value will became 1 only if it is selected
if bag == 1:
print(addbag)
# print meal only if it is selected, meal value will became 1 only if it is selected
if meal == 1:
print(addmeal)
# print the Total price
print(f'Total:{Total}')
However, it does not print like I want to. For example if I choose ticket no 1 and to add one bag, the output is:
Receipt:
Ticket : 500
Bag : 200
0
Total: 850
But I only want the total to be 700 and I don't want the "0" on the line after "Bag". It stills adds the meal price to the total price and the "0" comes from the line before the while-loop. I put the meal price and the print string for meal in option 3 so I don't know why it still adds the meal price?
So what I want it to look like in the receipt is:
Receipt:
Ticket : 500
Bag : 200
Total: 700
Any ideas on how I can solve this? :)
I'm trying to use menus to accepts menu options that append an empty list that acts as a cart. When the list is done with i have the option to add more lists if necessary. In the end im supposed to calculate the total number of carts, total number of items, and the total price. The first issue is the calcuation of carts is wrong as it treats every new entry as list rather than na item, which elads to the item count being wrong as well for each cart. Along with this, i get "TypeError: unsupported operand type(s) for +: 'int' and 'str'" when trying calculating the final price and im just not sure what to do
def main():
#Flag for full checking out or not
checkout = False
#Flag to start a new cart or not
new_cart = True
#Placeholder list
cart = []
#List of items
book_list = [['My Own Words', 18.00], ['Grant', 24.50], ['The Overstory', 18.95], ['Becoming', 18.99]]
elec_list = [['HP Laptop', 429.50], ['Eyephone', 790.00], ['Bose Speakers', 220.00]]
cloth_list = [['T-shirt', 9.50], ['Shoes', 45.00], ['Pants', 24.00], ['Nationals Hat', 32.00]]
groc_list = [['Coho Salmon', 12.50], ['Spaghetti', 2.75], ['Milk', 3.99], ['Eggs', 1.99], ['Flat Tire Ale', 9.95]]
while checkout == False or new_cart == True:
#Main Menu
if checkout == False:
#Main Item menu
print("""
1 - Books
2 - Electronics
3 - Clothes
4 - Groceries
c - Continue to checkout
""")
choice = input("Select one of the categories or checkout(1-4 or 'c'): ")
#Variable to return user to past menu
Return = False
if choice == '1':
while Return == False:
#Sub item menu
print("""
1 - "My Own Words", $18.00
2 - "Grant", $24.50
3 - "The Overstory", $18.95
4 - "Becoming", $18.99
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item =='3' or item == '4':
#Adds item onto the the cart
cart.append(book_list[int(item)-1])
elif item == 'x':
#Returns user to main menu
Return = True
else: print("Invalid input try again")
elif choice == '2':
while Return == False:
#Sub item menu
print("""
1 - HP Laptop, $429.50
2 - EyePhone 10, $790.00
3 - Bose 20 Speakers, $220.00
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item == '3':
#Adds item onto the the cart
cart.append(elec_list[int(item)-1])
elif item == 'x':
Return = True
else:
print("Invalid input try again")
elif choice == '3':
while Return == False:
#Sub item menu
print("""
1 - T-shirt, $9.50
2 - Shoes, $45.00
3 - Pants, $24.00
4 - Nationals Hat, $32.00
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item == '3':
#Adds item onto the the cart
cart.append(cloth_list[int(item)-1])
elif item == 'x':
Return = True
else:
print("Invalid input try again")
elif choice == '4':
while Return == False:
#Sub item menu
print("""
1 – Coho Salmon, $12.50
2 − Spaghetti, $2.75
3 – Milk, $3.99
4 – Eggs, $1.99
5 – Flat Tire Ale, $9.95
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item == '3' or item == '4' or item == '5':
#Adds item onto the the cart
cart.append(groc_list[int(item)-1])
elif item == 'x':
Return = True
else:
print("Invalid input try again")
elif choice == 'c':
checkout = True
print(cart)
else: print("Invalid input, please try again!")
else:
print("Do you want a new cart y/n")
choice = input()
if choice == 'y':
checkout = False
#Create new cart
cart.append([])
elif choice == 'n':
#Proceed to item summary
new_cart = False
else:
print("Invalid Option, Choose again")
#Print total number of carts
print("Total number of carts :",len(cart))
for v in range(len(cart)):
#Increment for each existing cart
print("Cart",v+1)
#Add total number of items within every cart
print("Total Number of items:",len(cart[v]))
#Add total price of items within every cart
print("Total cost of the items: $",sum(cart[v]))
main()
Your cart contains a list of items which themselves are array:
example, i ran your code and your cart looks like this:
[['My Own Words', 18.0], ['My Own Words', 18.0], ['My Own Words', 18.0], ['My Own Words', 18.0]]
you're trying to apply a sum on a position of an array, so for example when you do
sum(cart[0]) you call sum on ['My Own Words', 18.0] so your code tries to do:
'My Own Words'+18 which gives a type error.
if all you need is the just the total price you could just append the prices instead of the whole items, or you could simply append the prices to a seperate array and call sum on that
I'm new in python, and I'm trying to make a simple quit, if the Input is empty or less then One int.
I'm getting an error which says - ValueError: invalid literal for int() with base 10: '', when entering nothing, just a enter on launch.
import sys
import os
import getpass
def clear(): return os.system('clear')
ballance = 500.00
# Garage Stockas
Wood_InStock = 600
Weed_InStock = 300
Gun_InStock = 15
Gun_Ammo_InStock = 500 * 30 # X30 Total 15000
# Kainos
Gun_Ammo_Price = 15.50
Wood_Price = 3.50
Weed_Price = 9.50
Gun_Price = 250.50
# Produktai
medis = '~ Elemental Wood ~'
weed = '~ Indoor Kush ~'
gun = '~ Shotgun ~'
gun_ammo = '~ Shotgun ammo 30x ~'
# Inventory
Wood_Inventory = 0
Weed_Inventory = 0
Gun_Inventory = 0
Gun_Ammo_Inventory = 0
# No Money
Not_Enough_Money = '~ Sorry you dont have enough money'
while True:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
elif Shop_Pasirinkimas == 1:
clear()
WoodPirkimo_Skaic = int(input("How much {medis} would you like to buy? ".format(medis=medis) + "Wood Now in Stock - {woodins}\n".format(woodins=Wood_InStock)))
# Price per wood - 3.50
ballance -= ( Wood_Price * WoodPirkimo_Skaic)
Wood_Inventory += WoodPirkimo_Skaic
Wood_InStock -= WoodPirkimo_Skaic
print("~ In stock of {}, left {}".format(medis,Wood_InStock))
print("~ Successfully bought {}, Your Ballance is {}\n".format(medis,ballance))
print('Inventory:')
print("~ You have {}, of {}\n".format(Wood_Inventory,medis))
Buymore = input("Would you like to buy anything more?... Yes/No\n")
if "Yes" in Buymore or "yes" in Buymore:
continue
elif "No" in Buymore or "no" in Buymore:
break
else:
break
Let's look at only this part of the code:
while True:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
The empty user input will be passed to int(), but an empty string cannot be converted to an int! So an error is raised.
What you should instead is to not convert the input to int first, and treat it as a string:
while True:
Shop_Pasirinkimas = input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
elif int(Shop_Pasirinkimas) == 1: # convert to int here
clear()
...
int(x,base) function will return the integer object from any number or string. Base defaults to 10. If x is the string, its respective numbers should be within possible values with respect to that base.
As, nothing is entered, it's considered as invalid literal.
Hence, Please use the input as string which can solve the issue easily.
If user doesn't input an integer you will encounter an exception in Shop_Pasirinkimas = int(input(...)). Besides int has no len() so this will also cause error len(Shop_Pasirinkimas). You can do the following to accomplish what you are trying
while True:
try:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if Shop_Pasirinkimas < 1:
sys.exit("SOrry")
elif Shop_Pasirinkimas == 1:
clear()
WoodPirkimo_Skaic = int(input("How much {medis} would you like to buy? ".format(medis=medis) + "Wood Now in Stock - {woodins}\n".format(woodins=Wood_InStock)))
# Price per wood - 3.50
ballance -= ( Wood_Price * WoodPirkimo_Skaic)
Wood_Inventory += WoodPirkimo_Skaic
Wood_InStock -= WoodPirkimo_Skaic
print("~ In stock of {}, left {}".format(medis,Wood_InStock))
print("~ Successfully bought {}, Your Ballance is {}\n".format(medis,ballance))
print('Inventory:')
print("~ You have {}, of {}\n".format(Wood_Inventory,medis))
Buymore = input("Would you like to buy anything more?... Yes/No\n")
if "Yes" in Buymore or "yes" in Buymore:
continue
elif "No" in Buymore or "no" in Buymore:
break
else:
break
except ValueError:
sys.exit("SOrry")
Just started learning Python about two months ago, on and off. Still a beginner, but I come from a solid C background. I might not do things the "Python" way, as C is so heavily ingrained into me, but I got my script working. However, I just added a while loop so that I can run it multiple times and exit on user request. The while loop just exits no matter what the input, though. Pretty sure I have my indentation correct. Here's the whole script (with my API key removed). It's the very outside loop, the while finished == 0:
#!/usr/bin/env python3
import sys
import requests
import json
import time
appid = {'key': 'xxxxxxxxxxxxxxx'}
kingston = {'city': "/Canada/Kingston.json", 'city_str': "Kingston, Ontario"}
ottawa = {'city': "/Canada/Ottawa.json", 'city_str': "Ottawa, Ontario"}
toronto = {'city': "/Canada/Toronto.json", 'city_str': "Toronto, Ontario"}
vancouver = {'city': "/Canada/Vancouver.json", 'city_str': "Vancouver, British Columbia"}
sydney = {'city': "/Australia/Sydney.json", 'city_str': "Sydney, Australia"}
wellington = {'city': "/zmw:00000.1.93436.json", 'city_str': "Wellington, New Zealand"}
london = {'city': "/zmw:00000.1.03772.json", 'city_str': "London, UK"}
bergen = {'city': "/zmw:00000.1.01317.json", 'city_str': "Bergen, Norway"}
def cityquery(query):
searchresult = requests.get("http://autocomplete.wunderground.com/aq", params={'query': query})
results = json.loads(searchresult.text)
for index, x in enumerate(results['RESULTS'], start=1):
print(index, x['name'])
selection = input("Please select a number from the list:")
return {'city': results['RESULTS'][int(selection) - 1]['l'] + ".json", 'city_str': results['RESULTS'][int(selection) - 1]['name']}
def getWeather():
finished = 0
while finished == 0:
selected = 0
print("Please choose a city, or enter s to search by city name:")
print("\t1)", toronto['city_str'])
print("\t2)", sydney['city_str'])
print("\t3)", london['city_str'])
print("\t4)", vancouver['city_str'])
print("\t5)", ottawa['city_str'])
print("\t6)", kingston['city_str'])
print("\t7)", wellington['city_str'])
print("\t8)", bergen['city_str'])
while selected == 0:
citynumber = input("Enter a city number or s: ")
if citynumber == '1':
current_city = toronto
selected = 1
elif citynumber == '2':
current_city = sydney
selected = 1
elif citynumber == '3':
current_city = london
selected = 1
elif citynumber == '4':
current_city = vancouver
selected = 1
elif citynumber == '5':
current_city = ottawa
selected = 1
elif citynumber == '6':
current_city = kingston
selected = 1
elif citynumber == '7':
current_city = wellington
selected = 1
elif citynumber == '8':
current_city = bergen
selected = 1
elif citynumber == 's':
searchterm = input("Please type the first few characters of a city name: ")
current_city = cityquery(searchterm)
selected = 1
else:
print("Invalid entry!")
current_time = time.localtime()
print("The current time is", str('{:02d}'.format(current_time[3])) + ":" + str('{:02d}'.format(current_time[4])) + ":" + str('{:02d}'.format(current_time[5])))
print("Forecast for", current_city['city_str'])
#Current conditions
print("Getting current conditions...")
page = requests.get("http://api.wunderground.com/api/" + str(appid['key']) + "/conditions/q/" + current_city['city'])
values = json.loads(page.text)
# DEBUG print(page.text)
# DEBUG print(current_city)
temp = float(values['current_observation']['temp_c'])
if values['current_observation']['windchill_c'] == 'NA':
temp_wc = temp
else:
temp_wc = float(values['current_observation']['windchill_c'])
print("The temperature in", current_city['city_str'], "is currently", str('{:.2f}'.format(temp)) + "C feeling like", str('{:.2f}'.format(temp_wc)) + "C")
pressure_in = float(values['current_observation']['pressure_in'])
pressure_kp = float(values['current_observation']['pressure_mb']) / 10.0
print("The barometric pressure is", str('{:.2f}'.format(pressure_in)), "inches of mercury or", str('{:.1f}'.format(pressure_kp)), "kilopascals.")
wind_speed = float(values['current_observation']['wind_kph'])
wind_gust = float(values['current_observation']['wind_gust_kph'])
wind_dir = str(values['current_observation']['wind_dir'])
if wind_gust == 0:
print("The wind is", str('{:.2f}'.format(wind_speed)), "km/h from the", wind_dir)
else:
print("The wind is", str('{:.2f}'.format(wind_speed)), "km/h, gusting to", str('{:.2f}'.format(wind_gust)), "km/h from the", wind_dir)
#Forecast
print("Getting forecast...")
page = requests.get("http://api.wunderground.com/api/" + str(appid['key']) + "/forecast/q" + current_city['city'])
values = json.loads(page.text)
for x in [0, 1, 2, 3, 4, 5]:
print("Forecast for", values['forecast']['txt_forecast']['forecastday'][x]['title'], ":", values['forecast']['txt_forecast']['forecastday'][x]['fcttext_metric'])
waiting = 0 # loop until valid input
while waiting == 0:
exit = input("Press x to exit or c to check again...")
if exit == 'x' or 'X':
finished = 1
waiting = 1
elif exit == 'c' or 'C':
finished = 0
waiting = 1
else:
finished = 0
waiting = 0
if __name__ == "__main__":
getWeather()
There is an error in line 110 (if elif block inside while waiting). Correct statement would be:
if exit == 'x' or exit == 'X'
your statement reads if exit == 'x' or 'X' which is incorrect. It is comparing exit to x but not to X. What you want to write is if exit is equal to x or exit is equal to X but you have coded for either exit is equal to x or X is True. Now 'X' is always true and it is independent of your input (because you are not comparing it to any variable) and hence the loop exits irrespective of input. Same mistake is there in elif and else block.
This is very much like C