I have a problem.
I want to display all my records in "view" command, but it only displays the last record.
How do I solve the problem?
Please help me , thank you!
my code:
initial_money = int(input('How much money do you have? '))
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
global rec
rec = records[0]
global amt
amt = records[1]
global initial_money
initial_money += int(amt)
def view(initial_money, records):
print("Here's your expense and income records:")
print("Description Amount")
print("------------------- ------")
print('{name:<20s} {number:<6s}'.format(name = rec,number = amt))
print('Now you have {} dollars.'.format(initial_money))
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
elif command == 'view':
view(initial_money, records)
Output
How much money do you have? 100
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tomato -50
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
salary 100
What do you want to do (add / view / delete / exit)? view
Here's your expense and income records:
Description Amount
------------------- ------
salary 100
Now you have 150 dollars.
output I want:
------------------- ------
tomato -50
salary 100
Now you have 150 dollars.
I will use a dictionary to hold them instead:
initial_money = int(input('How much money do you have? '))
mr = {}
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
global rec
rec = records[0]
global amt
amt = records[1]
global mr
global initial_money
mr[rec] = int(amt)
initial_money += mr[rec]
def view(initial_money, records):
print("Here's your expense and income records:")
print("Description Amount")
print("------------------- ------")
for r,a in mr.items():
print('{name:<20s} {number:<6s}'.format(name = r,number = str(a)))
print('Now you have {} dollars.'.format(initial_money))
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
elif command == 'view':
view(initial_money, records)
Test:
How much money do you have? 100
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tomato -50
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
salary 100
What do you want to do (add / view / delete / exit)? view
Here's your expense and income records:
Description Amount
------------------- ------
tomato -50
salary 100
Now you have 150 dollars.
You need to make records into a list of the records you inserted. Currently you are overwriting it each time you call add.
make records an array outside your main loop
In your main loop push the results of the call to add into your array In your view function
you then need to loop over the array to view all the results.
Also for bonus, stop using global in your add function, It's considered bad form
Related
I'm very new to coding and I've managed to create the equation but I just can't wrap my head around the function side of things - The task is to create a menu which adds 20% VAT - 10% discount and 4.99 delivery fee - I was originally going to repeat the equation and change the price variable but a function would be much better and will require less coding but I just can't figure out how to perform it - Any help would be appreciated.
def menu():
print("[1] I7 9700k")
print("[2] GTX 1080 graphics card")
print("[3] SSD 2 Tb")
price = 399;
discount_percentage = 0.9;
taxed_percentage = 1.2;
Delivery_cost = 4.50;
Vat_price = (price*taxed_percentage)
Fin_price = (Vat_price*discount_percentage)
Final_price = (Fin_price+Delivery_cost)
print("Final price including delivery:", "£" + str(Final_price))
menu()
option = int(input("Enter your option: "))
while option != 0:
if option ==1:
print("I will add equations later :)")
elif option ==3:
print("I will add")
else:
print("You numpty")
print()
menu()
option = int(input("Enter your option: "))```
Since you already have a function for menu() I am going to assume the difficulty is in passing the values. You can define the function as follows:
def get_total_price(price, discount, tax, delivery_cost):
price *= tax
price *= discount
price += delivery_cost
return price
product_price = get_total_price(399, 0.9, 1.2, 4.50)
If the tax, discount and delivery are the same each time, you can hard-code those values into the function and only give the price as a variable as such:
def get_total_price(price):
price *= 1.2
price *= 0.9
price += 4.5
return price
product_price = get_total_price(399)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
I want to ask the user if they are members and if so, give them a 5% discount on the seats they have purchased, if they are not members, there is no discount. I also want to display that discounted price. Also, how would I go about adding up all the final prices and displaying those as well? I don't know where to start with this, any help is appreciated, thanks. There may be some formatting issues, but here is my code:
def main():
print("Your final price for Orchestra seats will be $",get_orchp())
print("Your final price for Center seats will be $",get_centerp())
def get_orchp():
ORCH_SEATS = 75
frontseats = float(input('Enter the number of Orchestra seats you want to purchase : '))
Finalorchp = ORCH_SEATS * frontseats
member = str(input('Are you a member of the local theater group? Enter y or n: '))
if member == 'y':
discount = 0.5
disc = Finalorchp * discount
Findiscorchp = Finalorchp - disc
elif member == 'n':
print('There is no discount for non-members')
return Finalorchp
return findiscorchp
def get_centerp():
CENTER_SEATS = 50
middleseats = float(input('Enter the number of Center Stage seats you want to purchase : '))
Finalcenterp = CENTER_SEATS * middleseats
return Finalcenterp
main()
This is how I would resolve all of your questions:
def main():
orchp = get_orchp()
centerp = get_centerp()
print(f"Your final price for Orchestra seats will be ${orchp}")
print(f"Your final price for Center seats will be ${centerp}")
print(f'Your final price for all tickets is {orchp + centerp}')
def get_orchp():
ORCH_SEATS = 75
frontseats = float(input('Enter the number of Orchestra seats you want to purchase : '))
Finalorchp = ORCH_SEATS * frontseats
member = str(input('Are you a member of the local theater group? Enter y or n: '))
if member == 'y':
Finalorchp *= .95
return Finalorchp
else:
print('There is no discount for non-members')
return Finalorchp
def get_centerp():
CENTER_SEATS = 50
middleseats = float(input('Enter the number of Center Stage seats you want to purchase : '))
Finalcenterp = CENTER_SEATS * middleseats
return Finalcenterp
main()
Please note these
I change the location of the calls to your functions and set a variable to receive them
I changed the prints for the final price to an f string to receive the variables from the functions
Changed Finalorchp to the pythonic version of variable = variable * .95 right under the if member statement
Changed the else statement in get_orchp to else in the event that the user doesn't only put y or n (you could add onto this to have fault tolerance of if it isn't y or n then do something else)
Added another final price print with an f string to add the two variables that receive the 2 variables from the functions.
This code does what you want.
you can see that in the code I have returned both price and discount amount from the getorchp() function as a tuple and using which I have printed the actual price and discount in the main function. If the user is not a member the discount will be zero and in the main function, I have added both orchestra seats and center seat price and printed the total final price. This code answers all questions you have asked
def main():
orc = get_orchp()
print("Your final price for Orchestra seats will be $",orc[0], " and discount is ", orc[1])
cen = get_centerp()
print("Your final price for Center seats will be $",cen)
print("total final price", orc[0]+cen)
def get_orchp():
ORCH_SEATS = 75
frontseats = float(input('Enter the number of Orchestra seats you want to purchase : '))
Finalorchp = ORCH_SEATS * frontseats
member = str(input('Are you a member of the local theater group? Enter y or n: '))
if member == 'y':
discount = 0.5
disc = Finalorchp * discount
Findiscorchp = Finalorchp - disc
return (Findiscorchp, disc)
elif member == 'n':
print('There is no discount for non-members')
return (Finalorchp, 0)
def get_centerp():
CENTER_SEATS = 50
middleseats = float(input('Enter the number of Center Stage seats you want to purchase : '))
Finalcenterp = CENTER_SEATS * middleseats
return Finalcenterp
main()
I am coding a program that simulates someone making a purchase in a grocery store. I am displaying all the products and the price and I am prompting the user to input all the products they went to buy separated by commas. I want the program to check if the input is in the dictionary of product and add it to the cart with the use of a loop. Before adding it to cart the program needs to check if the input is valid, meaning if the item is in the list of products to buy. When the user selects an item to buy, I want the program to ask the user for the quantity of that item, so how many of the item they want to buy. At the samThen the program will calculate the total of all the products, then calculate the tax value, 24% of the total, and then return a subtotal that includes tax. Here is what I have so far:
def calculatetotal(slist, produce):
# for each item on the shoping list look up the cost & calculate total price
item_price = 0
subtotal = 0
VAT = 0
final_total = 0
basket = {}
for item in slist:
item_price = produce.get(item)
basket[item] = item_price
subtotal = subtotal + item_price
basket["Subtotal"] = subtotal
#calculating VAT
VAT = subtotal * 0.24
basket["VAT"] = VAT
#calculating price with tax
final_total = subtotal + VAT
basket["Total"] = final_total
# print off results
return basket
def main():
# set up grocery list with prices
produce={"Rice":5.00, "Bread":2.00, "Sugar":1.5, "Apple":0.75, "Cereal":3.75, "Gum": 1.00, "Water": 1.75, "Soda": 2.00}
# process input from the user - get a shopping list
item = input("Please enter the items that you want to buy: ")
slist = []
while(item != 'stop'):
if not (item in slist):
slist.append(item)
item = input("Please enter the items that you want to buy: ")
result = calculatetotal(slist, produce)
print(result)
main()
I've gotten most of it, but the small changes that I mentioned above, I can't figure out what to do. I forgot to mention that asking for the quantity of the item and checking if the user input has to be done with a loop. Any input is very much appreciated. Please show the change of code. Thank you in advance.
In this case I would simply go for a while loop
while True:
item = input("Please enter the items that you want to buy: ")
if item == 'Stop':
break
elif item not in produce or item in slist:
# error message or whatever
else:
num = int(input("Enter Quantity"))
# other operations
I have to write a program that writes a file for a company and analyzes the sales data.
request_countryname function has to validate the user's input is at least 2 characters long
request_sales function has to accept 2 parameters (product and country), request the user for input on the total sales for each product of that country, and validate that the amount is numeric and non negative
request_data function will iteratively request country names from the user using the above functions and will ask if the user wants to add another country. Once the user is finished, the program will display how many records were added to the file. The program will write a file name (sales_data.txt)
analyze_data function will calculate the average sales per country for each type of product, total amount of sales for each product type, and total amount of sales
I am having trouble with the analyze_data function. I keep getting an error saying some of my variable from the request_data function are undefined. I believe this is happening because these variables (such as software_accumulator) are defined locally, not globally. I tried calling the request_data function at the beginning of my analyze_data function to call the information I wrote in the file, but I am still getting an error. I am also not sure if I correctly used accumulators to calculate the totals for each product type.
How do I fix this?
#Request country name from user
#Country name must be at least 2 characters long
def request_countryname():
character_length = 2
while True:
country = input("Please enter the country's name: ")
if len(country) < character_length or not country.isalpha():
print("Name must be at least 2 characters.")
else:
return country
#Request total sales for each product type for the user's country
#Input must be numeric and non negative
def request_sales(product, country_name):
flag = -1
while flag < 0:
sales = input("Please enter the total sales for " + product + " in " + country_name + ": $ ")
try:
sales = float(sales)
except ValueError:
print("Amount must be numeric")
else:
if sales < 0 :
print("Amount must be numeric and and non-negative. ")
else:
flag = 1
return sales
#Iteratively requests country names from the user and asks for totals
#Once the user finishes inputting countries, program will store data to a file
#Program will display total number of records added
def request_data(sales_data):
sales_data = open(sales_data, "w")
count = 0
software_accumulator = 0
hardware_accumulator = 0
accessories_accumulator = 0
again = "y"
while again == "y" or again == "Y":
country_name = request_countryname()
software = request_sales("software", country_name)
hardware = request_sales("hardware", country_name)
accessories = request_sales("accessories", country_name)
#Write data to file
sales_data.write(country_name + '/n')
sales_data.write(software + '/n')
sales_data.write(hardware + '/n')
sales_data.write(accessories + '/n')
count += 1
software_accumulator += software
hardware_accumulator += hardware
accessories_accumulator += accessories
#Request country names from user
again = input("Do you want to add another country? (Enter y/Y for Yes: ")
#Displays total number of records added
print(count, " record(s) successfully added to file")
sales_data.close()
#Calculates and displays information
def analyze_data(sales_data):
sales_data = open(sales_data, "r")
sales_data = request_data(sales_data)
#Calculates total software of all country inputs
total_software = software_accumulator
#Calculates total hardware of all country inputs
total_hardware = hardware_accumulator
#Calculates total accessories of all country inputs
total_accessories = accessories_accumulator
#Calcuates average software
average_software = total_software / count
#Calcuates average hardware
average_hardware = total_hardware / count
#Calcuates average accessories
average_accessories = total_accessories / count
#Calculates total sales
total_sales = total_software + total_hardware + total_accessories
#Prints and displays calculations
print("----------------------------")
print()
print("Average software sales per country: $ ", format(average_software, ',.2f'))
print("Average hardware sales per country: $ ", format(average_hardware, ',.2f'))
print("Average accessories sales per country: $ ", format(average_accessories, ',.2f'))
print()
print("Total software sales: $ ", format(total_software, ',.2f'))
print("Total hardware sales: $ ", format(total_hardware, ',.2f'))
print("Total accessories sales: $ ", format(total_accessories, ',.2f'))
print()
print("Total sales: $ ", format(total_sales, ',.2f'))
#Defines main function
def main():
request_data("sales_data.txt")
analyze_data("sales_data.txt")
#Calls main function
main()
You are correct in your hunch it has to do with the scope the variable are in, pay attention to where you define your variables, once you exit a function all variables in that functions scope will be gone. Don't use global variables, but return values you need from a function.
I suggest using an IDE to develop in as well, they will tell you when you are accessing a variable that is not in scope (ie not defined) - PyCharm or VSCode are both highly accessible
IDE says function isn't returning value
IDE says variable not defined
I have a problem.
I wanna add the same record but the old one will be replaced by a new one! I want both of them exist so I can see what I've done.
How do I solve the problem? Please help me!
Thank you!
my code:
initial_money = int(input('How much money do you have? '))
mr={}
add_mr={}
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
global mr
global rec
rec = records[0]
global amt
amt = records[1]
for r, a in mr.items():
i = 0
while (r, i) in add_mr:
i += 1
add_mr[(r, i)] = a
global initial_money
mr[rec] = int(amt)
initial_money += mr[rec]
def view(initial_money, records):
print("Here's your expense and income records:")
print("Description Amount")
print("------------------- ------")
for r,a in mr.items():
print('{name:<20s} {number:<6s}'.format(name = r,number = str(a)))
print('Now you have {} dollars.'.format(initial_money))
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
elif command == 'view':
view(initial_money, records)
The output:
How much money do you have? 1000
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
ewq 87
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
ewq 87
What do you want to do (add / view / delete / exit)? view
Here's your expense and income records:
Description Amount
------------------- ------
tree 87
Now you have 1174 dollars.
Output I want:
------------------- ------
tree 87
tree 87
Instead of using a dictonary such that Mr = {"ewq": 87} you could instead use a list of all of them such that Mr = [("ewq", 87), ("ewq", 87)]
This would make it so that if you have a duplicate it won't overwrite. As dictionaries can only have one per key
Edit: You would do this by replacing the first part that says mr = {} with mr = [] and then whenever you call addmr you can instead just use mr.append(value) which will add the value to the list
You actually can do this with a dict. In stead of one item per key use one list per key.
if rec not in mr:
mr[rec] = []
mr[rec].append(amt)
Such that mr = {"ewq": [87, 87]}