I can't even explain. Here is my code
foods = {12345670 : 'orange(s)',
87654325 : 'pineapple(s)'}
loop = 10
while loop == 10:
full_list = input("Type: ")
if full_list == 'end':
break
amount = int(input("Amount: "))
subtotal = 0
item = int(full_list)
if item in foods:
print("That would be {} {}".format(amount, foods[item]))
if full_list == '12345670':
price = (0.50 * amount)
print("Added Orange(s)")
print("Added "+str(price))
subtotal = subtotal + price
if full_list == '87654325':
price = (1.00 * amount)
subtotal = subtotal + price
print("Added Pineapple(s)")
print("Added "+str(price))
print("Your subtotal is " +str(subtotal))
I'm trying to get my subtotal to change accordingly to what the user purchases, I haven't finished making my list of purchasable items and so I don't want to change the name of the variable every time. What is the problem here? Why doesn't the variable subtotal change?
foods = {12345670 : 'orange(s)',
87654325 : 'pineapple(s)'}
loop = 10
subtotal = 0 # <------ moved it outside of the while loop
while loop == 10:
full_list = input("Type: ")
if full_list == 'end':
break
amount = int(input("Amount: "))
item = int(full_list)
if item in foods:
print("That would be {} {}".format(amount, foods[item]))
if full_list == '12345670':
price = (0.50 * amount)
print("Added Orange(s)")
print("Added "+str(price))
subtotal = subtotal + price
if full_list == '87654325': #should be an elif not an if
price = (1.00 * amount)
subtotal = subtotal + price
print("Added Pineapple(s)")
print("Added "+str(price))
print("Your subtotal is " +str(subtotal))
Every time you looped you restarted the total cost to 0 and it only kept the latest price. Move it outside of the while loop where I commented and you should be fine. Also use elif if you want to chain similar if statements together.
You have the following
if full_list == '12345670'
But it will never enter this if statement because your input type is an integer not a string. Do this without the single quotes instead:
if full_list == 12345670
Related
Ticket sales. Calculate the total, based on the number of half price and full price tickets. If the user is a student, give a 50 cent discount for each ticket. Ask user to input number of child tickets, number of adult tickets, and if the person is a student (y/n). Keep asking until user enters a 0 and a 0
FULL_PRICE = 10.00
HALF_PRICE = FULL_PRICE % 2
giveDiscount = True
def calculatePrice(nHalfPriceTix, nFullPriceTix, giveDiscount):
if giveDiscount:
total = (nHalfPriceTix * HALF_PRICE) + (nFullPriceTix * FULL_PRICE) - .5
else:
total = (nHalfPriceTix * HALF_PRICE) + (nFullPriceTix * FULL_PRICE)
return total
while True:
print()
nChildTickets = input('How many child tickets do you want? ')
nChildTickets = int(nChildTickets)
nAdultTickets = input('How many adult tickets do you want? ')
nAdultTickets = int(nAdultTickets)
if (nChildTickets == 0) or (nAdultTickets == 0):
break
yesOrNo = input('Are you a student (y/n)? ')
if yesOrNo.lower() == 'y':
isStudent = True
else:
isStudent = False
thisTotal = calculatePrice(nChildTickets, nAdultTickets)
print('Your total is $' + thisTotal)
print()
totalSales = totalSales + thisTotal
print('Total of all sales $', totalSales)
Also to add on, this:
print('Your total is $' + thisTotal)
should be:
print('Your total is $' + str(thisTotal))
since the '+' operator in print() can only accept strings(not a float).
Or you could change the + to a ,.
calculatePrice function requires 3 arguments and got only two:
thisTotal = calculatePrice(nChildTickets, nAdultTickets)
so i think for that to work you need to pass isStudent because you didnt use it
thisTotal = calculatePrice(nChildTickets, nAdultTickets,isStudent)
I'm a new learner for python and I'm trying to make a program that prints in invoice of all the items + their price + their quantity. each item is in separate line.
I have got tot he point where I print each item in a line, but I keep overwriting the old values by the last value entered. how can I prevent this?
this is the code:
print("This program prints your invoices."
"\nPlease enter the item identification, item cost and quantity sold when promted."
"\nEnter 'done' when no more items"
"\n=========================================")
saveqty= ()
savetprice=()
qtysum= 0 #quantity =qty for short
sumprice=0
list1 = []
totalprice=0
while True:
itemid = input('Item identification: ')
if itemid == "done":
break
if len(itemid)<3:
print("item identification should be at least 3 characters long, try again")
continue
else:
list11 = list[itemid]
list1 +=[itemid]
qtysold = input("Qty sold: ")
try:
qtysold =int(qtysold)
except ValueError:
print("must be an integer value, try again")
continue
qtysum+=qtysold
try:
itemprice = float(input("Item price: "))
savetprice= (itemprice)
except ValueError:
print("item price must be numerical value, try again")
continue
totalprices= (qtysold*itemprice)
totalprice+=totalprices
for elem in list1:
print(qtysold,'x ',elem, '# ', savetprice, 'SAR', '===', totalprices)
total = sumprice
itemtotal = qtysum
print("=========================================\nNo. of items purchased: ", itemtotal,"\nTotal price is: ", totalprice, "SAR")
Below is the code that fixes your problem
print("This program prints your invoices."
"\nPlease enter the item identification, item cost and quantity sold when promted."
"\nEnter 'done' when no more items"
"\n=========================================")
saveqty = ()
savetprice = ()
qtysum = 0 # quantity =qty for short
sumprice = 0
list1 = []
totalprice = 0
while True:
itemid = input('Item identification: ')
if itemid == "done":
break
if len(itemid) < 3:
print("item identification should be at least 3 characters long, try again")
continue
qtysold = input("Qty sold: ")
try:
qtysold = int(qtysold)
except ValueError:
print("must be an integer value, try again")
continue
qtysum += qtysold
try:
itemprice = float(input("Item price: "))
savetprice = (itemprice)
except ValueError:
print("item price must be numerical value, try again")
continue
totalprices = (qtysold * itemprice)
totalprice += totalprices
list1.append((itemid, qtysold, savetprice, totalprices))
for elem, qtysold, savetprice, totalprices in list1:
print(qtysold, 'x ', elem, '# ', savetprice, 'SAR', '===', totalprices)
total = sumprice
itemtotal = qtysum
print("=========================================\nNo. of items purchased: ", itemtotal, "\nTotal price is: ", totalprice, "SAR")
Output:
This program prints your invoices.
Please enter the item identification, item cost and quantity sold when promted.
Enter 'done' when no more items
=========================================
Item identification: 123
Qty sold: 5
Item price: 20
Item identification: 456
Qty sold: 3
Item price: 30
Item identification: done
5 x 123 # 20.0 SAR === 100.0
3 x 456 # 30.0 SAR === 90.0
=========================================
No. of items purchased: 8
Total price is: 190.0 SAR
Note: You need to save all the information (e.g., itemid, qtysold) in the while loop to list1 if you want to print them out later. Otherwise, qtysold and totalprices will always keep the last value when exiting the while loop. This explains the reason for the problem you are facing.
I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]
I am trying to create a simple program that contains a list of dictionaries. The grocery_history is the list of dictionaries, and the dictionary is grocery_item. Here is the code:
'''
The task is broken down into three sections.
Section 1 - User Input
Section 2 - loop through the grocery list
Section 3 - provide output to the console
'''
grocery_item = {}
grocery_history = []
stop = 'go'
while stop != 'q':
item_name = input("Item name:\n")
quantity = int(input("Quantity purchased:\n"))
cost = float(input("Price per item:\n"))
grocery_item['name'] = item_name
grocery_item['number'] = quantity
grocery_item['price'] = cost
grocery_history.append(grocery_item)
stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
print(grocery_history)
grand_total = 0
for grocery_item in range(0, len(grocery_history)):
item_total = grocery_history[grocery_item]['number'] * grocery_history[grocery_item]['price']
grand_total += item_total
print(str(grocery_history[grocery_item]['number']) + " " + grocery_history[grocery_item]['name'] + " # $%.2f" % grocery_history[grocery_item]['price'] + " ea \t$%.2f" % item_total)
item_total = 0.0
print("Grand total: $%.2f" % grand_total)
print(grocery_history)
In case you're wondering, the prompt for this assignment told me to use the variable grocery_item in my for loop. I normally would have chosen a different name since it becomes confusing. I also added a couple of print statements to print out the contents of grocery_history to see what's going wrong, and I confirmed it's when the dictionary is being added to the grocery_history list, that's when it for some reason updates existing dictionary items to match the new one being added. I can't figure out what I'm doing wrong. Any help would be greatly appreciated!
You need to define a new dictionary object each time in loop or else you end up using the same dictionary object so in effect replaces the already added one.
while stop != 'q':
grocery_item = {}
# ...
sample code should work
grocery_history = []
stop = 'go'
while stop != 'q':
item_name = input("Item name:\n")
quantity = int(input("Quantity purchased:\n"))
cost = float(input("Price per item:\n"))
grocery_item = {}
grocery_item['name'] = item_name
grocery_item['number'] = quantity
grocery_item['price'] = cost
grocery_history.append(grocery_item)
stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
print(grocery_history)
grand_total = 0
for grocery_item in range(0, len(grocery_history)):
item_total = grocery_history[grocery_item]['number'] * grocery_history[grocery_item]['price']
grand_total += item_total
print(str(grocery_history[grocery_item]['number']) + " " + grocery_history[grocery_item]['name'] + " # $%.2f" % grocery_history[grocery_item]['price'] + " ea \t$%.2f" % item_total)
item_total = 0.0
print("Grand total: $%.2f" % grand_total)
print(grocery_history)
the problem happened because you are repeating using same dict, although it adds to list each time, what you actually doing is keep updating the same reference so all content in the list becomes the same value
move dict inside solve the problem
This is because your loop does not create a new grocery_item object each time; it just updates the same grocery_item object over and over.
grocery_history ends up containing multiple references to this single object, in its latest state.
To fix this issue, move the line grocery_item = {} to be the first item underneath the while stop != 'q': loop. This will create a new object each time through the loop.
You can use map and sum to get grand_total
grocery_history = []
stop = 'go'
while stop != 'q':
grocery_item = {}
grocery_item['name'] = input("Item name:\n")
grocery_item['number'] = int(input("Quantity purchased:\n"))
grocery_item['price'] = float(input("Price per item:\n"))
grocery_history.append(grocery_item)
stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
grand_total = sum(map(lambda item: item['number'] * item['price'], grocery_history))
print("Grand total: $%.2f" % grand_total)
print(grocery_history)
Input:
Item name:
item
Quantity purchased:
2
Price per item:
1.2
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
q
Output:
Grand total: $2.40
[{'name': 'item', 'number': 2, 'price': 1.2}]
I'm not sure if I needed to post all of this but I thought I would include it all just in case. The assignment that I'm working on uses 3 dictionaries and functions to allow the user to add stocks, recommend a sale, and exit I'm currently having a problem with my GetSale or recommend sale function. The GetSale function should find the maximum expected value of selling a stock. The expected sale value of a stock is the current profit minus the future value of the stock:
Expected Sale value = ( ( Current Price - Buy Price ) - Risk * CurrentPrice ) * Shares
The GetSale function should calculate this value for each stock in the portfolio, and return the stock symbol with the highest expected sale value. When I call the GetSale function with option 2 under the Main function I always get "Highest selling stock is with a 0 profit margin." even after entering in different stocks. Is my GetSale function coded so that is what it returns and its not even checking the dictionary I'm new to this so not exactly sure where I went wrong.
Names = {}
Prices = {}
Exposure = {}
def AddName(StockNames, StockPrices, StockExposure):
TheStockName = input("Input stock name. ")
Prompt = "Input the stock symbol for " + TheStockName
Symbol = input(Prompt)
StockNames[Symbol] = TheStockName
StockPrices[Symbol] = None
StockExposure[Symbol] = None
return StockNames
def AddPrices(StockPrices):
while True:
Symbol = input("Input stock symbol for the stock and add price next. ")
if Symbol in Prices:
Prompt = input("Current buying price of " + Symbol + ": ")
BuyPrice = float(Prompt)
Prompt = input("Current selling price of " + Symbol + ": ")
SellPrice = float(Prompt)
StockPrices[Symbol] = [BuyPrice, SellPrice]
return StockPrices
else:
print("This stock does not exist.")
def AddExposure(StockExposure):
while True:
Symbol = input("Input stock symbol for the stock and add exposure next. ")
if Symbol in Exposure:
Prompt = input("Current number of " + Symbol + " stocks that have been purchased? ")
SharesOwned = float(Prompt)
Prompt = input("Current risk factor of " + Symbol + " share ownership? ")
RiskFactor = float(Prompt)
StockExposure[Symbol] = [SharesOwned, RiskFactor]
return StockExposure
else:
print("This stock does not exist.")
def AddStock():
AddName(Names, Prices, Exposure)
AddPrices(Prices)
AddExposure(Exposure)
def GetSale(Names, Prices, Exposure):
HighestStock = 0
HighestStockName = ''
for Stock in Names:
TotalProfit = ((Prices[Stock][1] - Prices[Stock][0]) - Exposure[Stock][1] * Prices[Stock] [0]) * Exposure[Stock][0]
if (TotalProfit > HighestStock):
HighestStock = TotalProfit
HighestStockName = Stock
print("Highest selling stock is", HighestStockName, "with a ", HighestStock, "profit margin.")
def Main():
keepGoing = True
while keepGoing:
print("Menu")
print("1: Add a stock")
print("2: Find the highest sale price")
print("3: Exit")
userResponseString = input("Input selection (1, 2 or 3): ")
try:
userInput = int(userResponseString)
except:
print("Invalid input.")
userChoice = 0
if (userInput == 1):
AddStock()
elif (userInput == 2):
GetSale(Names, Prices, Exposure)
else:
(userInput == 3)
print("Ending stock program.")
keepGoing = False
Main()