How do I sum given data in written file in python - python

My code runs almost correctly. The program needs to take in a country name, software/hardware/accessory sales, and then give the average for each category per country, total sales for each category, and overall total sales. If the users opt to enter a second, third, etc country, the averages and total must all be added together to find each calculation. My code currently calculates all of those things, but it does it for each country separately and it doesn't correctly count the number of countries added. I don't know why or how to fix it, please help!
def request_countryname():
country_name = input('Please enter the country\'s name: ')
while len(country_name) < 2:
print('Name must be at least two chracters')
country_name = input('Please enter the country\'s name: ')
return country_name
def request_sales(product_type, country_name):
sales = float(input('Please enter the total sales for ' + product_type + ' in ' + country_name + ": "))
while sales == type(str) or sales < 0:
print('Sales must be a non-negative numeric input')
sales = float(input('Please enter the total sales for', product_type, 'in', country_name))
return sales
def request_data(sales_data):
sales_data = open('sales_data.txt', 'w')
records = 0
add_country = True
while True:
records += 1
country_name = request_countryname()
soft_sales = request_sales('software', country_name)
hard_sales = request_sales('hardware', country_name)
acc_sales = request_sales('accessories', country_name)
sales_data.write(f'{country_name}\n{soft_sales}\n{hard_sales}\n{acc_sales}\n')
add_country = input('Do you want to add another country? (Enter y/Y for Yes, any other key to stop): ')
if add_country == 'y' or add_country == 'Y':
records += 1
request_data("sales_data.txt")
analyze_data("sales_data.txt")
else:
print(records, 'record(s) successfully added to the file.')
print('----------------------------------------------\n')
sales_data.close()
return sales_data
def analyze_data(sales_data):
sales_data = open ('sales_data.txt', 'r')
software_sales = []
hardware_sales = []
accessory_sales = []
read_file = sales_data.readline()
while read_file != '':
soft_sales = sales_data.readline()
hard_sales = sales_data.readline()
acc_sales = sales_data.readline()
software_sales.append(float(soft_sales))
hardware_sales.append(float(hard_sales))
accessory_sales.append(float(acc_sales))
read_file = sales_data.readline().rstrip('\n')
soft_average= sum(software_sales)/len(software_sales)
hard_average = sum(hardware_sales)/len(hardware_sales)
acc_average = sum(accessory_sales)/len(accessory_sales)
total_soft = sum(software_sales)
total_hard = sum(hardware_sales)
total_acc = sum(accessory_sales)
total_sales = float(total_soft + total_hard + total_acc)
print('Average software sales per country: $' + format(soft_average, ',.2f'))
print('Average hardware sales per country: $' + format(hard_average, ',.2f'))
print('Average accessory sales per country: $' + format(acc_average, ',.2f'))
print('')
print('Total software sales: $' + format(soft_average, ',.2f'))
print('Total hardware sales: $' + format(hard_average, ',.2f'))
print('Total accessory sales: $' + format(acc_average, ',.2f'))
print('')
print('Total sales: $' + format(total_sales, ',.2f'))
sales_data.close
def main():
request_data("sales_data.txt")
analyze_data("sales_data.txt")
main()
Edit: my professor said the problem was in the request_data function, specifically the "while True" part because I need to specify what is true, I just don't know what.

I'm going to try to answer your question, but also give you some refactoring pointers that may be helpful:
def request_country_name():
country_name = ""
while len(country_name) < 2:
print('Name must be at least two characters')
country_name = input('Please enter the country\'s name: ')
return country_name
def request_sales(product_type, country_name):
sales = ""
while sales == type(str) or sales < 0:
print('Sales must be a non-negative numeric input')
try:
sales = float(input(f"Please enter the total sales for {product_type} in {country_name}: "))
except:
pass
return sales
def read_record(record):
header = {'country_name': str,'soft_sales': float,'hard_sales': float,'acc_sales': float}
str_dict = dict(zip(list(header.keys()), record.replace("\n", "").split(",")))
return {k:header[k](v) for k,v in str_dict.items()}
def request_data(sales_data_file="sales_data.csv"):
records = 0
add_country = True
while True:
records += 1
country_name = request_country_name()
soft_sales = request_sales('software', country_name)
hard_sales = request_sales('hardware', country_name)
acc_sales = request_sales('accessories', country_name)
with open(sales_data_file, 'w') as writer:
writer.write(f'{country_name},{soft_sales},{hard_sales},{acc_sales}\n')
add_country = input('Do you want to add another country? (Enter y/n): ').upper()
if add_country == 'Y':
analyze_data(sales_data_file)
else:
print(F"{records} record(s) successfully added to the file.\n----------------------------------------------\n")
break
def analyze_data(sales_data_file="sales_data.csv"):
latest_country_records = {}
with open(sales_data_file) as reader:
for line in reader.readlines():
data = read_record(line)
latest_country_records[data['country']] = data
total_soft = sum([v['soft_sales'] for v in latest_country_records.values()])
soft_average= total_soft/len(latest_country_records)
total_hard = sum([v['hard_sales'] for v in latest_country_records.values()])
hard_average = total_hard/len(latest_country_records)
total_acc = sum([v['acc_sales'] for v in latest_country_records.values()])
acc_average = total_acc/len(latest_country_records)
total_sales = total_soft + total_hard + total_acc
print('Average software sales per country: $' + format(soft_average, ',.2f'))
print('Average hardware sales per country: $' + format(hard_average, ',.2f'))
print('Average accessory sales per country: $' + format(acc_average, ',.2f'))
print('')
print('Total software sales: $' + format(total_soft, ',.2f'))
print('Total hardware sales: $' + format(total_hard, ',.2f'))
print('Total accessory sales: $' + format(total_acc, ',.2f'))
print('')
print('Total sales: $' + format(total_sales, ',.2f'))
def main():
request_data("sales_data.txt")
analyze_data("sales_data.txt")
if __name__ == "__main__":
main()
Alright, so after some refactoring -- I think your biggest issue was you weren't handling the file handlers well (I replaced with context managers) which led to some odd structuring -- ie. your "request_data" function was being called recursively (by itself) in an unnecessary way.
Some other things to note, in your final print out you were printing the avg in place of the totals -- also you avg & total calculations overlapped a bit (reuse the total and calc it first).
Last note, and one worth keeping front of mind -- 9 times out of 10 there's an existing, established data structure -- lean on those. In this case, csv is your friend, in others json will be helpful.
Storing the data in different rows leads to unneeded complexity, and if possible should be avoided.
FWIW -- I haven't run/tested this code so there may be a few errors

Related

how i can solve : can't multiply sequence by non-int of type 'float' (python)

i'm just newbie for python , can anyone help me this code, im stuck for a week for this problem
here my code:
price = {
"Espresso": 5.80,
"Americano": 6.90,
}
currency = "$"
print ("welcome coffee machine!\t")
name = input ("can i get your name?\n")
print ("what do you like to order mr/ms " + name + "\n" )
menu = ("Espresso, Americano")
print (menu)
menu = (input())
quantity = input("How many " + menu + " would you like?\n")
quantity = str(input())
#im stuck at here! T_T
if menu == "Espresso" :
price = 5.80
total = quantity * price
quantity.append(quantity)
price.append(price)
print(total)
elif menu == "Americano":
price = 6.90
total = quantity * price
quantity.append(quantity)
price.append(price)
print(total)
else:
menu()
#invoice receipt
print("Thank you for order " + name + ", please wait your " + menu + " at counter\n")
hopefully someone/somebody can help me to solve this problem T_T
You are getting error because of this line:
quantity = str(input())
price = 5.80
total = quantity * price
You are multiplying string with float.
TypeError: can't multiply sequence by non-int of type 'float'
thank you for you help, i found my answer
here the correct code:
menu = "Espresso, Americano"
print (menu)
order = input()
#changed the quantity variable to an integer so that it can be used in mathematical operations!
quantity = int(input("How many " + order + " would you like?\n"))
#added a total variable and called the calculate_total function to calculate the total
# price based on the quantity and price of the order.
def calculate_total(quantity, price):
total = quantity * price
return total
total = calculate_total(quantity, price[order])

Calculate the total of tickets and give a discount to student. There is a problem with function of the calculation the total and loops

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)

Return multiple values in a function

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]

How would I go about fixing this block of code?

The code below is supposed to output the following if you choose employee
Do you wish to enter data for an (E)mployee, a (S)alesperson, or would you like to (Q)uit?: e
Enter the name of the employee: (employee name)
Enter (employee name) hourly pay rate: (pay rate)
Enter (employee name) hours worked: (hours worked ```
Employee data:
Employee name: (employee name)
Employee hourly pay: (hourly pay)
Hours worked: (hours worked)
Pay: (pay)
That is if you choose the to enter data for an employee ^^^
Here is the following output if you would like the choose the following data for a Salesperson
Do you wish to enter data for an (E)mployee, a (S)alesperson, or would you like to (Q)uit?: s
Enter the name of the employee: (employee name)
Enter (employee name) hourly pay rate: (hourly pay)
Enter the number of hours worked by (employee name): (hours worked)
Enter the amount of sales made by (employee name): (sales made)
Enter the commission percentage that will be earned by (employee name): (commission percentage)
Salesperson data:
Employee name: (employee name)
Employee hourly pay: (hourly pay)
Hours worked: (hours worked)
Sales: (sales made)
Commission percentage: (commission percent)
Pay: (pay)
Here is the entire block of code that is executing all of this. Keep in mind that this has to be done using classes and polymorphism.
class Employee:
def __init__(self, hours_worked, hourly_rate):
self.__hours_worked = 0
self.__hourly_rate = 0
def set_hours_worked(self, hours_worked):
self.__hours_worked = hours_worked
def get_hours_worked(self):
return self.__hours_worked
def set_hourly_rate(self, hourly_rate):
self.__hourly_rate = hourly_rate
def get_hourly_rate(self):
return self.__hourly_rate
def calc_pay(self):
return self.__hourly_rate * self.__hours_worked
def __str_(self):
print()
string1 = 'Employee data: ' + '\n' + 'Employee name: ' + employee_name + '\n' + 'Employee hourly pay rate: ' + employee_pay + '\n' + 'Hours worked: ' + employee_hours + '\n' + 'Pay: ' + employee_pay
class Salesman(Employee):
def __init__(self, weekly_sales, commission, hours_worked, hourly_rate):
Employee.__init__(self, hours_worked, hourly_rate)
self.__weekly_sales = 0
self.__commission = 0
def set_weekly_sales(self, weekly_sales):
self.__weekly_sales = weekly_sales
def get_weekly_sales(self):
return self.__weekly_sales
def set_commission(self, commission):
self.__commission = commission
def get_commission(self):
return self.__commission
def calc_pay(self):
return Employee.calc_pay(self) + (self.__weekly_sales * self.__commission)
def __str__(self):
print()
string2 = 'Salesperson data: ' + '\n' + 'Employee name: ' + salesperson_name + '\n' + 'Employee hourly pay rate: ' + str(
salesperson_pay) + '\n' + 'Hours worked: ' + salesperson_hours + '\n' + 'Sales: ' + salesperson_sales + '\n' + 'Commission percentage: ' + str(
salesperson_commission) + '\n' + 'Pay: ' + str(salesperson_pay)
go_on = 'y'
while go_on == 'y':
input1 = input('Do you wish to enter data for an (E)mployee, a (S)alesperson, or would you like to (Q)uit?: ')
if input1 == 'e' or 'E':
employee_name = input('Enter the name of the employee: ')
employee_pay = input('Enter ' + employee_name + ' hourly pay rate: ')
employee_hours = input('Enter the number of hours worked by ' + employee_name + ': ')
employee_pay_rate = employee_pay * int(employee_hours)
employee = Employee(employee_name, employee_pay, employee_hours, employee_pay_rate)
print(employee)
if input1 == 's' or 'S':
salesperson_name = input('Enter the name of the employee: ')
salesperson_pay = float(input('Enter ' + salesperson_name + ' hourly pay rate: '))
salesperson_hours = input('Enter the number of hours worked by ' + salesperson_name + ': ')
salesperson_sales = input('Enter the amount of sales made by ' + salesperson_name + ': ')
salesperson_commission = float(input('Enter the commission percentage that will be earned by ' + salesperson_name + ': '))
salesperson = Salesman(salesperson_pay, salesperson_hours, salesperson_sales, salesperson_commission)
print(salesperson)
else:
go_on = 'n'
I am sure I got mostly everything right but I'm running into a couple problems and I don't know how to fix them.
Error: you are passing 5 arguments in the while loop to Employee with self included.
When taking input as a string from the user, use raw_input instead
of input.
input1 == "e" or "E" is always true. Do input1 == "e" or input1 == "E"
This way you are making use of the while loop to add as many users as needed.
And also some additional points:
You have a base class Employee whose constructor or init accepts (self, hours_worked, hourly_rate)
recommended: (self, name, hours_worked, hourly_rate)
In class Salesman's __init__ method, try to maintain the order of arguments passed where the parent class Employees arguments come first.
recommended: `class Salesman(Employee):
def __init__(self, name, hours_worked, hourly rate, weekly_sales, commission):
Employee.__init__(self, name, hours_worked, hourly_rate)
self.__weekly_sales = 0
self.__commission = 0`

Python stock portfolio program

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()

Categories