I'm trying to create a menu for a POS like system. I have my gift card balances with their numbers and I'm trying to incorporate this in a menu. In the menu for example, if a user click the number '1', I want the menu to prompt the user for the gift card number in which they will need to enter the correct gift card number (giftnum1). If the user does not click on a valid number or does not enter the correct gift card, I would like the menu to ask the user to click on a valid number or if the user enters the wrong gift card number, I would like for the menu to ask the user to check the gift card number and try again. I am new at this, so I know that most of my menu code is wrong and could be corrected somehow, but I'm not sure how to do this and all other posts relating to this do not make sense with this post.
Here is my code that I have:
gift1 = 100
gift2 = 13.50
gift3 = 67.40
giftnum1 = 123456
giftnum2 = 998765
giftnum3 = 456789
print("Here are your current gift cards with the current balances: " + "$" + str(gift1) + " with the gift \ncard number of " + str(giftnum1) + ", $" + str(gift2) + " with a gift card number of " + str(giftnum2) + ", and $" + str(gift3) + " with a gift card number of " + str(giftnum3) + ".")
#making the POS system
def itemmenu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
print ("1. Nike Shoes ($100)")
print ("2. Bluetooth Headphones ($67.40)")
print ("3. Gloves ($13.50)")
print ("4. Exit")
loop = True
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
input("Please enter the correct gift card to buy the Nike Shoes: ")
if buyitems == giftnum1:
print("You have successfully entered the correct gift card to buy the Nike Shoes, please follow the directions to be sent a confirmation email.")
if buyitems != giftnum1:
print("You have entered an incorrect gift card number.")
elif buyitems == 2:
input("Please enter the correct gift card to but the Bluetooth Headphones: ")
if buyitems == giftnum2:
print("You have successfully entered the correct gift card to buy the Bluetooth Headphones, please follow the directions to be sent a confirmation email.")
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
input("Please enter the correct gift card to buy the Nike Shoes: ")
if buyitems == giftnum1:
You aren't saving the result of the second input() call, so buyitems is still the same value it was before.
You probably want something like this:
if buyitems == 1:
giftcard = int(input("Please enter the correct gift card to buy the Nike Shoes: "))
if giftcard == giftnum1:
Please try below code :
gift1 = 100
gift2 = 13.50
gift3 = 67.40
giftnum1 = 123456
giftnum2 = 998765
giftnum3 = 456789
print("Here are your current gift cards with the current balances: " + "$" + str(gift1) + " with the gift \ncard number of " + str(giftnum1) + ", $" + str(gift2) + " with a gift card number of " + str(giftnum2) + ", and $" + str(gift3) + " with a gift card number of " + str(giftnum3) + ".")
#making the POS system
def itemmenu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
print ("1. Nike Shoes ($100)")
print ("2. Bluetooth Headphones ($67.40)")
print ("3. Gloves ($13.50)")
print ("4. Exit")
loop = True
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
while loop:
giftcardno = int(input("Please enter the correct gift card to buy the Nike Shoes: "))
if giftcardno == giftnum1:
print("You have successfully entered the correct gift card to buy the Nike Shoes, please follow the directions to be sent a confirmation email.")
break
else:
print("You have entered an incorrect gift card number. Try again")
elif buyitems == 2:
giftcardno = input("Please enter the correct gift card to but the Bluetooth Headphones: ")
if giftcardno == giftnum2:
print("You have successfully entered the correct gift card to buy the Bluetooth Headphones, please follow the directions to be sent a confirmation email.")
else:
print("You have entered an incorrect gift card number. Try ag")
else:
break
Hetal Thaker and John Gordon answers are what you are looking for. One issue that may arise though, as you have probably noticed, is that your loop becomes endless even when you select the correct gift card number. To fix that simply set your loop variable to False once an item is purchased and it will work.
I have played around with your code a bit and made some transformations using dictionaries and less hard coding. Check it out, it might help in case you have larger data of variables - you can simply put them into the 2 dictionaries and the rest will work on it's own. Note that I did not implement any logic on what happens when the user selects "Exit" as I am not sure what behavior exactly you expect from the program for that. It would also be good to add logic in case the correct gift card is entered but its balance is not enough.
gift1_balance = 100
gift2_balance = 13.50
gift3_balance = 67.40
gift1_num = 123456
gift2_num = 998765
gift3_num = 456789
gift_cards = {gift1_num: gift1_balance, gift2_num: gift2_balance, gift3_num: gift3_balance}
merch_to_sell = {"Nike Shoes": [100, 1], "Bluetooth Headphones": [67.40, 2], "Gloves": [13.50, 3]}
print("Here are your current gift cards with the current balances:")
for key, value in gift_cards.items():
print(f"${value} with the gift card number of {key}")
def item_menu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
index = 1
for key, value in merch_to_sell.items():
print(f"{index}. {key} (${value[0]:.2f})")
index += 1
print(f"{index}. Exit")
is_item_bought = False
while not is_item_bought:
item_menu()
number_of_item = int(input("Enter the number corresponding to the item that you would like to buy: "))
current_item = 0
current_price = 0
current_index = 0
get_gift_num = 0
for k, v in merch_to_sell.items():
current_item = k
current_price = v[0]
current_index = v[1]
if is_item_bought:
break
if number_of_item == current_index:
get_gift_num = int(input(f"Please enter the correct gift card to buy the {current_item}: "))
for k, v in gift_cards.items():
if get_gift_num == k and gift_cards[k] == current_price:
print(f"You have successfully entered the correct gift card to buy the {current_item}, please follow the directions to be sent a confirmation email.")
is_item_bought = True
break
if not is_item_bought:
print("You have entered an incorrect gift card number.")
If you take this code, you can refactor it and eliminate some unnecessary variables within it and optimize it even further.
Cheers!
Related
I want the user to pick an item from the shop and I want to use a loop to keep track of the prices(the value in the dictionary) to add up and keep a running total after every input from user. If the user inputs something that is not in the dictionary, it should say that it does not exist.
thanks in advance for help
def main():
machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7}
for key, value in machine.items():
print(key,value)
print("------------------------------")
selection = input("Please choose the number of the item you would like to purchase: ")
total=0
for i in machine:
if selection=="1":
print("You chose shirt and your total is: $", machine["1.shirt: $"])
elif selection=="2":
print("You chose shirt and your total is: $", machine["2.pants: $"])
elif selection=="3":
print("You chose shirt and your total is: $", machine["3.sweater: $"])
elif selection=="4":
print("You chose shirt and your total is: $", machine["4.socks: $"])
elif selection=="5":
print("You chose shirt and your total is: $", machine["5.hat: $"])
else:
print("Your option does not exist. Your total is: ",total)
You should update the value of total every time a choice is made. See example below
def main():
machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7}
total=0
for key, value in machine.items():
print(key,value)
print("------------------------------")
while True: # Keep Looping
selection = input("Please choose the number of the item you would like to purchase: ")
if selection=="1":
total += machine["1.shirt: $"];
print("You chose shirt and your total is: $", total)
elif selection=="2":
total += machine["2.pants: $"];
print("You chose shirt and your total is: $", total)
else:
print("Your option does not exist. Your total is: ",total)
break
When I use this code, my aim is to try and make sure that any input will not break the code like letters or numbers not between 0-3. But when i use this code the whole list isn't coming up. How would i fix this?
The output should look like this
Hello Megan the four games avaliable are:
0 Mario Cart
1 Minecraft
2 Angry Birds
3 Grabd Theft Auto
What number game do you want? h
Please choose a valid number
What number game do you want? 23
Please choose a number between 0 and 3
What number game do you want? 1
You have chosen Minecraft
Instead, the output is
Hello the four games avaliable are:
0 Mario Cart
What number game do you want? 2
1 Minecraft
What number game do you want? h
Please enter a valid value
The code i am using is:
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
try:
gametype = int(input("What number game do you want? "))
while gametype <0 or gametype >3:
print (" Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a valid value " )
return gametype
game ()
I have also tried another way, using 'while True' before 'try' but the program says that is an invalid syntax.
SECOND TRY
I have used this new code, but again it won't let me run the code as it says I have an invalid syntax when I put While True, with True highlighted in red.
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
while True:
try:
gametype = int(input("What number game do you want? "))
if 0 <= gametype <= 3 :
return game
print ("Please enter a value between 0 and 3 ")
except ValueError:
print ("Please enter whole number from 0 to 3 " )
return game
game ()
I think you want something like this:
gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]
def game(name):
""" Ask user what game they would like to play """
print ("Hello, {}, the four available games are:".format(name))
for gamenum, gamename in enumerate(gamelist):
print(gamenum, ":", gamename)
while True:
try:
gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= 3:
return gamenum
print("Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a whole number from 0 to 3")
name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])
demo output
What's your name? Megan
Hello, Megan, the four available games are:
0 : Mario Cart
1 : Minecraft
2 : Angry Birds
3 : Grand Theft Auto
What number game do you want? 4
Please enter a value between 0 and 3
What number game do you want? Minecraft
Please enter a whole number from 0 to 3
What number game do you want? 2
You chose Angry Birds
The main change I made to your code is to put the try.. except stuff inside a while True block, so we keep asking for input until we get something valid. I also used enumerate to print each game with its number. That's neater than your while gamecount < 4: loop.
If you have to print the list of games using a while loop then you can do it like this:
gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]
def game(name):
""" Ask user what game they would like to play """
print ("Hello, {}, the four available games are:".format(name))
gamenum = 0
while gamenum < len(gamelist):
print(gamenum, ":", gamelist[gamenum])
gamenum += 1
while True:
try:
gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= 3:
return gamenum
print("Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a whole number from 0 to 3")
name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])
I made gamelist a global list so we can access it outside the game function. We don't need to use the global statement in the function because we aren't changing gamelist. In general, you should avoid using the global statement.
so I've been working on this code for a little bit just to test my abilities and I've run into a brick wall. For some reason my code is breaking out of my for loop. If I say I want to see how much 2 rooms cost it goes through the first one fine but them asks me how many rooms I want to check again. If I input 2 again, it will go through it once and then go on through the rest of the code normally. I have two for loops setup the exact same as each other but for some reason one works and the other doesn't. I'm probably making a stupid mistake but I've been trying to fix it for ages now but no cigar. Appreciate all help!
def start():
print ("Welcome to Caroline's Painting and Decorating cost estimator")
print ("Here you can see an estimate to see how much the job will cost")
print ("First though, you have to enter a few details about the job")
customerNumber = input ("Please enter your customer number ")
dateofEstimate = input ("Please enter the current date ")
def roomCalculator():
surfaceAreaCost = 0
totalPrice = 0
price = 0
count = 0
rooms = int(input("Please enter the number of rooms that require painting "))
for i in range(0, rooms):
roomName = input ("What room needs decorating? ")
wallsNumber = int(input("How many walls are in the room? "))
wallpaper = input ("Is there any wallpaper thats needs to be removed? Enter Y for yes and N for no ")
if wallpaper == "Y".lower():
surfaceAreaCost + 70
for i in range(0, wallsNumber):
count = count + 1
print ("Please enter the dimensions for wall", count)
height = int(input("How high is the wall? "))
width = int(input("How long is the wall? "))
surfaceAreaWall = height*width
wallCost = surfaceAreaWall * 15
price = surfaceAreaCost + wallCost
employeeType = input ("What employee would you like? Enter AP for apprentice or FQ for Fully-Qualified ")
if employeeType == "AP".lower():
price = price + 100
print ("You are having an apprentice do the job")
print ("The price for the", roomName, "without V.A.T is", price)
return price
elif employeeType == "FQ".lower():
price = price + 250
print ("You are having a Fully-Qualified employee to do the job")
print ("The price for the", roomName, "without V.A.T is", price)
return price
Your error is a result of nested for loops, because you use variable i in both. This causes an error since you change value of variable i in first for loop with second for loop. Rename variable in second for loop with j for instance.
Thanks all for the help! It was a stupid error on my part. I used 3.4.4 at my school computer and 3.5.1 at home. It all worked anyway.
I'm a beginner in Python programming, therefore I'm following a course where we have to submit assignments every week.
The current assignment is to write a program where the user can Open, and Close and account, can Deposit and Withdraw money, and List the accounts (i.e. view all accounts and balance according to specific account).
My main problem is that the balance (which starts at 0) is the same for every account, while every account should have its own balance!
I came this far:
# -*- coding: utf-8 -*-
def print_menu():
print "1. List Account(s)"
print "2. Open an Account"
print "3. Close an Account"
print "4. Withdraw money"
print "5. Deposit Money"
print "6. Quit"
print
accounts = {}
menu_choice = 0
print_menu()
#balance = {}
balance = 0
while True:
menu_choice = int(input("Type in a number (1-6): "))
print
if menu_choice == 1:
print "Accounts"
for x in accounts.keys():
print "Accountnumber:", x, "with balance €", balance
print
elif menu_choice == 2:
print "Enter a new Accountnumber"
number = input("New accountnumber: ")
#phone = input("Number: ")
accounts[number]=balance
print "Accountnumber", number, "opened."
elif menu_choice == 3:
print "Close an Accountnumber"
number = input("Accountnumber: ")
if number in accounts:
#accounts[number]=balance
del accounts[number]
print "Accountnumber", number, "is closed."
else:
print "Accountnumber", number, "was not found"
#elif menu_choice == 4:
#print("Lookup Number")
#name = input("Name: ")
#if name in numbers:
# print("The number is", numbers[name])
#else:
# print(name, "was not found")
elif menu_choice == 4:
print "Withdraw money from Account."
number = input("Accoutnnumber: ")
if number in accounts:
withdraw = float(input("How much money would you like to withdraw? > "))
if withdraw < balance:
#accounts[number]=balance
numbers[balance] -= withdraw
#balance vann number 444 bijv. !!
print "Your new balance is €", balance
else:
print "There are no sufficient funds on this accountnumber"
elif menu_choice == 5:
print "Deposit money onto Account."
number = input("Accountnumber: ")
if number in accounts:
deposit = float(input("How much money would you like to deposit? > "))
#accounts[number]=balance
balance += deposit
#balance vannn number 444 bijv. !!
print "Your new balance is €", balance
else:
print "That accountnumber does not exist."
elif menu_choice == 6:
print "Quit."
break
else:
print "Please enter a number between 1 and 6."
print
print_menu()
# Ook nog ff instellen dat wanneer input geen iets anders is,
# dan gewoon netjes afluisten, geen rare foutcodes !!
The problem is that you are using "balance" in a wrong way. It's far better if you use accounts like a dictionary, where you have "accounts numbers" and "balance".
This way if you have something like:
accounts = {1:100, 2:1500, 3:0}
that means that the person with account numbered 1 has 100$, the second person with acc number 2 has 1500 and so on.
For example in choice 4 you are doing this:
elif menu_choice == 4:
print "Withdraw money from Account."
number = input("Accoutnnumber: ")
if number in accounts:
withdraw = float(input("How much money would you like to withdraw? > "))
if withdraw < balance:
#accounts[number]=balance
numbers[balance] -= withdraw
#balance vann number 444 bijv. !!
print "Your new balance is €", balance
else:
print "There are no sufficient funds on this accountnumber"
But this is better:
elif menu_choice == 4:
print "Withdraw money from Account."
number = input("Accoutnnumber: ")
if number in accounts:
withdraw = float(input("How much money would you like to withdraw? > "))
balance = accounts[number]
if withdraw < balance:
accounts[number] -=withdraw
print "Your new balance is €", accounts[number]
else:
print "There are no sufficient funds on this accountnumber"
I hope this help with your homework.
So I'm coding a small project and I'm struggling with a certain aspect so far.
Here is the code:
import re
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = input(">>>")
print("Please enter your post code")
postCode = input(">>>")
print("Is your house a number, or a name?")
nameOrNumber = input(">>>")
if nameOrNumber == "number" or nameOrNumber == "Number":
print("Please enter your house number")
houseNumber = input(">>>")
elif nameOrNumber == "Name" or nameOrNumber == "name":
print("Please enter your house name")
houseName = input(">>>")
else:
print("Invalid")
house = (houseNumber) + (houseName)
address = (postCode) + ", " + (house)
print("Thank you for your information")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = input(">>>")
if clientDetailsCorrect == "no" or clientDetailsCorrect == "No":
clientDetails()
clientDetails()
Not sure what's going wrong as I haven't actually referenced the variable anywhere else. Someone help.
It would help if you posted the traceback.
That said, this line is the likely source of the problem:
house = (houseNumber) + (houseName)
The way your code is currently written, only one of houseNumber or houseName will be defined. So Python is likely complaining about the missing one.
Given how your code looks so far, it's probably better to just do:
print("Please enter your house name or number")
house = input(">>>")
And remove the house = (houseNumber) + (houseName) line.
Try this:
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator\n")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = raw_input(">>>")
print("Please enter your post code")
postCode = raw_input(">>>")
print("Please enter your hose number or name")
house = raw_input(">>>")
address = "{}, {}".format(postCode, house)
print("Thank you for your information.\n")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = raw_input(">>>")
if clientDetailsCorrect.lower().startswith('n'):
clientDetails()
Using raw_input is better, it will input everything as a string. Also it will allow users to not type quotations to input text (I assume you will run this from CLI). If you later on need to separate houses that are numbers from names Python has very good string methods you can use to do so many wonderful things, I used a couple of them to simplify your code :)
N