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? :)
Related
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())
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
"""read file and store into database"""
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
artist=[""]
song=[""]
album=[""]
genre=[""]
index=0
for line in f:
if index==0:
artist.append(line)
index=index+1
elif index==1:
song.append(line)
index=index+1
elif index==2:
album.append(line)
index=index+1
elif index==3:
genre.append(line)
index=index+1
elif index==4:
index=0
while 1:
selection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Search\n2.Recommend\n3.Edit\n4.Save\n"))
if selection == 1:
print "You selected Search"
searchselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Display All Songs\n2.Display All Artists\n3.Search By Artist\n4.Display All Genres\n5.Search by Genre\n6.Display All Playlists\n7.Search By Playlist\n"))
if searchselection == 1:
print '[%s]' % ''.join(map(str, song))
elif searchselection == 2:
print '[%s]' % ''.join(map(str, artist))
elif searchselection == 3:
artistsearch = str(raw_input("\nWhat artist are you searching for?\n"))
artist.index(artistsearch)
print value
elif searchselection == 4:
print '[%s]' % ''.join(map(str, genre))
elif searchselection == 5:
print "display"
elif searchselection == 6:
print "display"
elif searchselection == 7:
print "display"
break
elif selection == 2:
print "You selected recommend."
recommendselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Recommend by Song Title\n2.Recommend by Artist Name\n"))
if recommendselection == 1:
songrec = str(raw_input("Please enter the song title\n"))
elif recommendselection == 2:
artistrec = str(raw_input("Please enter the Artist's name\n"))
break
elif selection == 3:
print "You selected edit."
editselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Add a New Song\n2.Create New Playlist\n3.Add a song to a current playlist"))
if editselection == 1:
songadd = str(raw_input("Please enter the EVERYTHING\n"))
elif editselection == 2:
playistcreate = str(raw_input("Please enter the name of the Playlist\n"))
elif editselection == 3:
playlistadd = str(raw_input("Please enter the name of the playlist\n"))
break
elif selection == 4:
print "You selected Save."
f.close()
break
So that is what I have thus far. This is an ongoing python project, and right now I am stumped; I am trying to search by artist like if Justin Timberlake is typed in by the user as "artistsearch" then I want the index to be pulled so that I can match the index in the song list and display that information to the user.
Any help determining why Justin Timberlake is not a value on the list even though the name shows up when I run the display all artists option would be greatly appreciated.
Also being pointed in the right direction for matching list indexes would be great as well. This is an example of the tunes.txt:
Alicia Keys
No One
As I Am
R&B/Soul;Syl tunes
Everything But the Girl
Missing
Amplified Heart
Alternative;Syl tunes
Gathering Field
Lost In America
Lost In America
Rock
Ellie Goulding
Burn
Halcyon
Pop;Road tunes
Justin Timberlake
Mirrors
Mirrors (Radio Edit) - Single
Pop;Syl tunes
I think you should create a specific class for the data you want to store, and then create a list of objects that instantiate such class:
class Song():
"""Class to store the attributes for each song"""
def __init__ (self):
self.artist = ""
self.song = ""
self.album = ""
self.genre = ""
# List to store all the Song objects
songs_list = []
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
index=0
for line in f:
# Instantiate an empty Song object
s = Song()
if index == 0:
s.artist = line
index=index+1
elif index == 1:
s.song = line
index = index + 1
elif index == 2:
s.album = line
index = index + 1
elif index == 3:
s.genre = line
index = index+1
elif index == 4:
index = 0
songs_list.append(s)
So I'm getting a "array.append(str(con_owned[i])) IndexError: list index out of range" in my terminal and I'm kinda clueless any help?
Here is the rest of the code that was requested. I enter a number between 1 and 5 and i still get the error.
info = dict()
info['console'] = raw_input('The game console you own? ')
info['city'] = raw_input('The city you live in? ')
info['wconsole'] = raw_input('The console you would like? ')
info['rnum'] = raw_input('The number of consoles you own between 1 & 5? ')
info['rnum2'] = raw_input('A number between 1 and 12: ')
info['wcity'] = raw_input('Enter a number from 1 to 7: ')
info['float'] = float(input('Amount of money made per week (ex. 1.23): '))
if info['rnum'] >5:
info['rnum'] = 5
elif info['rnum'] <1:
info['rnum'] = 1
if info['rnum2'] >12:
info['rnum'] = 12
elif info['rnum2'] <1:
info['rnum2'] = 1
if info['wcity'] >7:
info['wcity'] = 7
elif info['wcity'] <1:
info['wcity'] = 1
con_owned = ['Xbox 360', 'Xbox One', 'Playstation 3', 'Playstation 4', 'Wii', 'WiiU', 'Xbox', 'Playstation 2', 'Gamecube']
con_owned.insert(0,str(info['console']))
array = []
for i in range(info['rnum']):
array.append(str(con_owned[i]))
console_list = ""
for console in array:
console_list = console_list + console + ", "
def calc_price():
decimal = info['float']
dollar_amount = decimal * 10
return dollar_amount
calc_price = calc_price()
wcities =['Paris', 'Hollywood', 'London', 'Hong Kong', 'Dublin', 'Orlando', 'Dallas']
wcity = wcities[(info['wcity']-1)]
message = '''I have a {info[console]} that I play at my house in the city of {info[city]}.
I currently own {into[rnum]} consoles. I really want to have a {info[wconsole]} and play it in {wcity}. One day I would like own {info[rnum2]} consoles.
I wish I could make ${calc_price} a week, I could afford a {info[dream]} and move to {live}.'''
messageFormatted = message.format(**locals())
print messageFormatted
Would you please mind providing the info dictionary? Because without it we can't replicate your problem on our end, which makes it harder to help you.
Although I'd bet that your info['rnum'] is larger than your console list, since it seems that your program tries to open a list index that does not exist.(ie, con_owned[9] since con_owned has values for indexes 0 through 8)
Edit :
Just provide the entire program, because I just tried what you posted with 5 for info['rnum'] and it worked without problem.
Edit 2 :
Here is the solution, replace :
if info['rnum2'] >12:
info['rnum'] = 12
elif info['rnum2'] <1:
info['rnum2'] = 1
with :
if info['rnum2'] >12:
info['rnum2'] = 12
elif info['rnum2'] <1:
info['rnum2'] = 1
You accidentally used rnum instead of rnum2 in that function.
Also, put all your raw_inputs that should be numbers in an int()
here :
info['console'] = raw_input('The game console you own? ')
info['city'] = raw_input('The city you live in? ')
info['wconsole'] = int(raw_input('The console you would like? '))
info['rnum'] = int(raw_input('The number of consoles you own between 1 & 5? '))
info['rnum2'] = int(raw_input('A number between 1 and 12: '))
info['wcity'] = int(raw_input('Enter a number from 1 to 7: '))
info['float'] = float(input('Amount of money made per week (ex. 1.23): '))
Try this:
info['rnum'] = int(raw_input('The number of consoles you own between 1 & 5? '))
Because I think that in info['rnum'], is not getting an int, and is getting an str.
I hope this helps
I have created this code to get 3 different options in 3 different places. Its actually a flash card program i hoped to get working but I can't. It goes into a endless loop and i have no idea why. There may also be other problems but i havent got to them yet but please tell me anyway. Keep the sam var names so i can understand easily. I have attached all the code. They is some more but its not been implemented yet.
There is also 3 lists each with 14 items but these won't go into code:
key_words = ['Cellulose', 'Respiration', 'Haemoglobin', 'Ventilation', 'Cartilage', 'Cytoplasm', 'Nucleus', 'Alveoli', 'Amino acids', 'Virus', 'White blood cells', 'Photosynthesis', 'Stomata', 'Vaccine', 'Fibre']
defs = ['Tough substance that makes up the cell walls of green plants', 'A chemical reaction that causes energy to be released from glucose', 'A substance which joins to oxygen and carries it round the body in the blood', 'Breathing', 'Tough, smooth substance covering the ends of bones to protect them', 'Jelly-like part of a cell where chemical reactions happen', 'Controls what happens inside a cell', 'Tiny air sacs in the lungs', 'Produced when proteins are digested', 'The smallest type of microbe', 'Can engulf bacteria or make antibodies', 'The process of turning carbon dioxide, water and light into glucose and oxygen', 'Small holes in the underside of a leaf', 'Dead or inactive forms of a microorganism', 'A nutrient that cannot be digested']
completed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
thanks
Callum
import random
option1 = random.randint(int(1), int(14))
option2 = random.randint(int(1), int(14))
option3 = random.randint(int(1), int(14))
while option1 == option2 or option1 == option3:
placement1 = random.randint(int(1), int(3))
while option2 == option3:
option2 = random.randint(int(1), int(3))
placement1 = random.randint(int(1), int(3))
placement2 = random.randint(int(1), int(3))
placement3 = random.randint(int(1), int(3))
while placement1 == placement2 or placement1 == placement3:
placement1 = random.randint(int(1), int(3))
while placement2 == placement1 or placement2 == placement3:
placement3 = random.randint(int(1), int(3))
print('What is the correct defenition for', key_words[option3])
place3 = 1
if placement1 == 1:
print('1: ', defs[option1])
elif placement1 == 2:
print('1: ', defs[option2])
elif placement1 == 3:
print('1: ', defs[option3])
place3 = '1'
if placement2 == 1:
print('2: ', defs[option1])
elif placement2 == 2:
print('2: ', defs[option2])
elif placement2 == 3:
print('2: ', defs[option3])
place3 = '2'
if placement3 == 1:
print('3: ', defs[option1])
elif placement3 == 2:
print('3: ', defs[option2])
elif placement3 == 3:
print('3: ', defs[option3])
place3 = '3'
choice = str(input('Enter 1, 2 or 3: '))
if choice == place3:
print('Well done, correct.')
a = completed[option3] + 1
completed[option3] += 1
else:
print('Inccorect. Have another look and we`ll come back later.')
In your first loop:
while option1 == option2 or option1 == option3:
placement1 = random.randint(int(1), int(3))
you never change the value of option1. If the condition is true going into the loop, it will remain true forever. Did you mean to use option1 instead of placement1?
You will never break out of your first loop.
while option1 == option2 or option1 == option3:
placement1 = random.randint(int(1), int(3))
The condition hinges on the values of option1, option2, and option3, which are never adjusted in the body of the loop. If the code enters the loop, it will stay there.
Incidentally, this code has numerous other serious problems and code smells. I don't have time to name them all.