I've been trying to have this data write to the "scenario_out.txt" file. However, when I run the code I do not any get errors but my text file does come out to empty, so no data was ever put into the file. . I'm reviewing my notes but I don't see where I went wrong.
# Display results of scenario
def file_save_flow(save_to_file, # save to a file object if save_to_file = True
file_object, # name of file object to save to
scen_year,
age,
s_bal,
bal_pv,
inv_gains,
ann_savings,
ss_payment,
major_inc,
major_exp,
tax_rate,
tar_ret_spend,
net_ret_spend,
ret_pre_tax_spend,
taxes,
end_bal
):
""" file_save_flow() test output
>>> out_file = open("scenario_out.txt","w")
>>> file_save_flow(save_to_file = True,
... file_object = out_file,
... scen_year = 0,
... age = 60,
... s_bal = 100000,
... bal_pv = 100000,
... inv_gains = 1000,
... ann_savings = 1000,
... ss_payment = 1000,
... major_inc = 1000,
... major_exp = 1000,
... tax_rate = 0.15,
... tar_ret_spend = 50000,
... net_ret_spend = 40000,
... ret_pre_tax_spend = 60000,
... taxes = 10000,
... end_bal = 120000
... )
>>> out_file.close()
>>> in_file = open("scenario_out.txt","r")
>>> print(in_file.read())
Year :0
Age :60
Start Bal :100,000.00
Start Bal PV :100,000.00
Invest Gains :1,000.00
Ann Savings :1,000.00
SS Payment :1,000.00
Major Inc :1,000.00
Major Exp :1,000.00
Tax Rate :15.00%
Targ Ret Spend :50,000.00
Net Ret Spend :40,000.00
Ret Pre-tax Spend:60,000.00
Taxes :10,000.00
End Bal :120,000.00
<BLANKLINE>
>>> in_file.close()
"""
#=============================My Code================================
if save_to_file == True:
print(' Year :' , scen_year,
'\n Age :',age,
'\n Start Bal :', (format(s_bal, ',.2f')) ,
'\n Start Bal PV :', (format(bal_pv, ',.2f')),
'\n Invest Gains :', (format(inv_gains, ',.2f')),
'\n Ann Savings :', (format(ann_savings,',.2f')),
'\n SS Payment :', (format(ss_payment, ',.2f')),
'\n Major Inc :', (format(major_inc, ',.2f')),
'\n Major Exp :', (format(major_exp, ',.2f')),
'\n Tax Rate :', (format(tax_rate, '.2%')),
'\n Targ Ret Spend :', (format(tar_ret_spend, ',.2f')),
'\n Net Ret Spend :', (format(net_ret_spend, ',.2f')),
'\n Ret Pre-tax Spend :', (format(ret_pre_tax_spend, ',.2f')),
'\n Taxes :', (format(taxes, ',.2f')),
'\n End Bal :', (format(end_bal, ',.2f')))
#============================================================================
# test function
out_file = open("scenario_out.txt","w") # set up the file object to write to
file_save_flow(save_to_file = True,
file_object = out_file,
scen_year = 0,
age = 60,
s_bal = 100000,
bal_pv = 100000,
inv_gains = 1000,
ann_savings = 1000,
ss_payment = 1000,
major_inc = 1000,
major_exp = 1000,
tax_rate = 0.15,
tar_ret_spend = 50000,
net_ret_spend = 40000,
ret_pre_tax_spend = 60000,
taxes = 10000,
end_bal = 120000
)
out_file.close()
in_file = open("scenario_out.txt","r") # read back the contents saved to the file
print(in_file.read())
in_file.close()
I've tied some bool variable to use as a flag , but still no luck.
At the moment, you're just printing your output to the console, rather than actually saving it to the file.
You probably want something like
if save_to_file == True:
output = (
' Year : ' + str(scen_year) +
'\n Age : ' + str(age) +
'\n Start Bal : ' + (format(s_bal, ',.2f')) +
'\n Start Bal PV : ' + (format(bal_pv, ',.2f')) +
'\n Invest Gains : ' + (format(inv_gains, ',.2f')) +
'\n Ann Savings : ' + (format(ann_savings,',.2f')) +
'\n SS Payment : ' + (format(ss_payment, ',.2f')) +
'\n Major Inc : ' + (format(major_inc, ',.2f')) +
'\n Major Exp : ' + (format(major_exp, ',.2f')) +
'\n Tax Rate : ' + (format(tax_rate, '.2%')) +
'\n Targ Ret Spend : ' + (format(tar_ret_spend, ',.2f')) +
'\n Net Ret Spend : ' + (format(net_ret_spend, ',.2f')) +
'\n Ret Pre-tax Spend : ' + (format(ret_pre_tax_spend, ',.2f')) +
'\n Taxes : ' + (format(taxes, ',.2f')) +
'\n End Bal : ' + (format(end_bal, ',.2f'))
)
file_object.write(output)
This creates a big string of your output data, then writes it to your file object.
If you remove all the fluff, your code looks exactly like this:
def file_save_flow(save_to_file, file_object, data):
if save_to_file == True:
print('Data: ', data)
out_file = open("scenario_out.txt", "w")
file_save_flow(save_to_file=True, file_object=out_file, data='data')
out_file.close()
in_file = open("scenario_out.txt", "r")
print(in_file.read())
in_file.close()
From that, it's immediately clear that your function does only one thing: it prints something if save_to_file is True and it prints nothing otherwise. It doesn't do anything with file_object.
So, although you create and open a file and pass the file handle to your function, you don't actually use it in the print() statement.
This would work:
def file_save_flow(save_to_file, file_object, data):
if save_to_file == True:
print('Data: ', data, file=file_object)
else:
print('Data: ', data)
Or, to avoiding repeating yourself:
def file_save_flow(save_to_file, file_object, data):
print('Data: ', data, file=file_object if save_to_file else None)
I'm doing an exercise and so far so good as the code (after some help from other threads) now works almost fine, but...can't get the right results as a math point of view.
Here it's the code:
#getting base prices from user
item1 = float(input('Enter the price of the first item: '))
item2 = float(input('Enter the price of the second item: '))
clubc = raw_input('Does customer have a club card? (Y/N): ')
tax = float(input('Enter tax rate, e.g. 5.5 for 5.5% tax: '))
basep = (item1 + item2)
print('Base price = ', basep)
#setting variables for calculation
addtax = (1 + (tax / 100))
#conditions for output
if item1 >= item2 and clubc == 'N':
priceafterd = float(item1 + (item2 / 2))
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * addtax)
print('Total price = ', totalprice)
elif item2 >= item1 and clubc == 'N':
priceafterd = float(item2 + (item1 / 2))
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * addtax)
print('Total price = ', totalprice)
if item1 >= item2 and clubc == 'Y':
priceafterd = float((item1 + (item2 / 2)) * 0.9)
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * var3)
print('Total price = ' + totalprice)
else:
priceafterd = float((item2 + (item1 / 2)) * 0.9)
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * var3)
print('Total price = ' + totalprice)
The exercise requires to write a program that computes how much a customer has to pay after purchasing two items, depending on a promo, club card and taxes.
The problem is with the results. As an example of inputs:
Enter price of the first item: 10
Enter price of the second item: 20
Does customer have a club card? (Y/N): y
Enter tax rate, e.g. 5.5 for 5.5% tax: 8.25
Base price = 30.00
Price after discounts = 22.50
Total price = 24.36
Instead, I got:
line 33, in <module>
print('Total price = ' + totalprice)
TypeError: cannot concatenate 'str' and 'float' objects
What's wrong with the syntax? Thanks a lot!
The problem
In the second conditional you wrote print('Total price = ' + totalprice) line instead of the print('Total price = ', totalprice), and the problem is in that:
totalprice has float type, meanwhile 'Total price = ' is the str and what you are trying to do is almost like str() + float(), and because python doesn't know how to concatenate string and float number it raises an exception.
How to solve
1) Use the same print('Total price = ', totalprice) line everywhere
Why does it work and print('Total price = ' + totalprice) does not?
Because print automatically converts everything to string representation, you can imagine print('Total price = ', totalprice) expression like that:
print(str('Total price = ') + " " + str(totalprice))
2) Convert float to str and concatenate strs
print('Total price = ' + str(totalprice))
str(totalprice) converts totalprice from float to the str and python knows how to concatenate strings together.
3) Formatting
"Total price = {}".format(3.14)" is equivalent to the "Total price = 3.14" string,
so print("Total price = {}".format(totalprice)) also will work
in python 3 we also have f-stings:
f"Total price = {3.14}" == "Total price = 3.14"
print(f"Total price = {totalprice}")
I got the program to loop and to ask the user for input. The problem is...when I try to print it keeps giving me an error. I need it to be in a specific format. Any help will be greatly appreciated.
Here is the error:
Traceback (most recent call last):
File "C:\Users\one\Desktop\Sherry\Python Folder\Week 4\w4_sgomez_assgn.py", line 40, in <module>
print('\t-----' + employee[0:4] + '-----\n')
TypeError: can only concatenate str (not "list") to str
Here is the code:
employee=[]
count=0
def addEmpl(employee, count):
if count < 5:
name=input('Enter Employee Name: ')
ssn=input('Enter Employee SSN: ')
phone=input('Enter Employee Phone: ')
email=input('Enter Employee Email: ')
salary=input('Enter Employee Salary: ')
report = name +',' + ssn + ',' + phone +','+ email +',' + salary
employee.insert(count,report)
count=count+1
def printEmpl(employee):
number=int(input('Press 0 to print list: '))
count = len(employee)
if (number>-1) and (number<1):
employee=employee[0]
employee='\n'.join([name,ssn, phone, email, salary])
employee[:]
print('\t-----' + employee[0:4] + '-----\n')
print('SSN: ' + employee[1] + '\n')
print('Phone: ' + employee[2] + '\n')
print('Email: ' + employee[3] + '\n')
print('Salary: $' + employee[4] + '\n')
print('\t-----------')
else:
return;
while True:
addEmp2=int(input('To add employee enter 1; to print enter 2; to search by ssn enter 3: '))
if (addEmp2 > 0)and(addEmp2 < 2):
addEmpl(employee, count)
else:
print('\t-----' + employee[0:4] + '-----\n')
print('SSN: ' + employee[1] + '\n')
print('Phone: ' + employee[2] + '\n')
print('Email: ' + employee[3] + '\n')
print('Salary: $' + employee[4] + '\n')
print('\t-----------')
Please find the correct code for function addEmpl below
def addEmpl(employee, count):
if count < 5:
name=raw_input('Enter Employee Name: ')
ssn=raw_input('Enter Employee SSN: ')
phone=raw_input('Enter Employee Phone: ')
email=raw_input('Enter Employee Email: ')
salary=raw_input('Enter Employee Salary: ')
report = name +',' + ssn + ',' + phone +','+ email +',' + salary
employee.insert(count,report)
count=count+1
Since, you have not given the complete error, so as per my best guess I tried to fix it. Please let me know if my understand is not correct.
The following line is triggering the error (it is in 2 places)
print('\t-----' + employee[0:4] + '-----\n')
You are using + operator on a string and list together employee[0:4] is a list.
Hence the error
TypeError: can only concatenate str (not "list") to str
The problem is the following line:
print('\t-----' + employee[0:4] + '-----\n')
You can't print it as is you need to convert the list to a string.
Something like
string=""
for x in range(len(employee)):
string=string+x
print('\t-----' + string + '-----\n')
The real problem here though is the structure you should really be using a class for this instead of a list like so.
class Employee:
def __init__(self,name,ssn,phone,email,salary):
self.name=name
self.ssn=ssn
self.phone=phone
self.email=email
self.salary=salary
empObj=Employee("RandomName",1231231,"444-777-8000","pretendEmail#somewhere.com",4000)
print(empObj.name)
My assignment was to write a program which extracts the first/last names, birth year, and ID from a file, manipulate that information to create a username and formatted ID, prompt the user for 3 test grades, calculate the average, and finally write all the information to a new file. This is the program I wrote, and the error I got is listed below the program.
Define main function
def main():
infile = open("studentinfo.txt", "r")
data = infile.read()
fName, lName, ID, year = data.split(",")
year = int(year)
Prompt the user for three test scores
grades = eval(input("Enter the three test scores separated by a comma: "))
Create a username
uName = (lName[:4] + fName[:2] + str(year)).lower()
converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
grade_1, grade_2, grade_3 = grades
Convert the grades to strings so they can be written to a new file
[grade_1, grade_2, grade_3] = [str(grade_1), str(grade_2), str(grade_3)]
Calculate the average
average =(grade_1 + grade_2+ grade_3)/3
Convert the average to a string
average = str(average)
Write the information the file
outfile = open("studentreport.txt", "w")
outfile.write("*******Student Report*******\nStudent Name:" + fName + " " + lName)
outfile.write("\nStudent ID: " + converted_id + "\n" + "Username: " + uName + "\n\n")
outfile.write("Grade 1: " + grade_1 + "\n" "Grade 2: " + grade_2 + "\n" + "Grade 3: " + grade_3 + "\n" + "Average: " + average)
infile.close()
outfile.close()
main()
Traceback (most recent call last):
File "C:/Users/ovi/Desktop/Python Project 1.py", line 34, in
main()
File "C:/Users/ovi/Desktop/Python Project 1.py", line 22, in main
average =(grade_1 + grade_2+ grade_3)/3
TypeError: unsupported operand type(s) for /: 'str' and 'int'
You need to convert your converted string grades to floats (or int)
average =(float(grade_1) + float(grade_2)+ float(grade_3))/3.0
average = str(average)
You need to convert the variables of type int to strings.
outfile.write("Grade 1: " + str(grade_1) + "\n" "Grade 2: " + str(grade_2) + "\n" + "Grade 3: " + str(grade_3) + "\n" + "Average: " + str(average))
OR
You could simply do like this..
>>> gr1 = 23
>>> gr2 = 45
>>> gr3 = 56
>>> total = gr1+gr2+gr3
>>> avg = total/3
>>> l = [gr1, gr2, gr3, total, avg]
>>> print("GRade 1: {} grade 2: {} grade 3: {} total: {} average : {}".format(*l))
GRade 1: 23 grade 2: 45 grade 3: 56