Trouble with python 3x with input and output from files
So, Im doing an assignment for my Computer science class and I'm having a slight problem. My professor wants us to add some lines of code that require the program to open up a .txt file and read the data from the .txt file through the program. In this case, my program is a monthly payment program.Usually, you'd ask the user to input how much he/she's borrowing, the interest rate, and the term in years. But, the data for all three of those are already pre-written in the .txt file, inwhich he wants us to read the data from. Now, I'm having trouble with my code.
This is my code:
import decimal
print("\t".join(s.rjust(15) for s in ("Payment", "Amount Paid", "Balance")))
print("-"*54)
filename = "LoanData.txt"
values = []
with open(filename) as f:
for line in f:
values.append([int(n) for n in line.strip().split(' ')])
for arr in values:
try:
balance,rate,term = arr[0],arr[1],arr[2]
except IndexError:
print ("Index error occured, a line doesn't have the crucial amount of entries.")
balance *= (1 + rate * term)
payment = balance / (12 * term)
total = 0
for month in range(12 * term):
if balance < payment:
payment = balance
print(("{: >15.2f}\t"*3)[:-1].format(payment, total, balance))
total += payment
balance -= payment
and this is the error im getting:
Traceback (most recent call last):
File "C:/Users/Python/Desktop/loan.py", line 11, in <module>
values.append([int(n) for n in line.strip().split(' ')])
File "C:/Users/Python/Desktop/loan.py", line 11, in <listcomp>
values.append([int(n) for n in line.strip().split(' ')])
ValueError: invalid literal for int() with base 10: '5.5'
This is what the file looks like:
5000 5.5 10
25000 10.0 10
100000 8.5 20
The reason this isn't working is because you are trying to convert a decimal value (such as 5.5) into an int. Now, even if you change it to convert to a float, an additional fix is still needed as you can't use a float as an iterator for a for loop:
1.Change
balance,rate,term = arr[0],arr[1],arr[2]
To
balance,rate,term = int(arr[0]),arr[1],int(arr[2])
2.Change:
values.append([int(n) for n in line.strip().split(' ')])
To
values.append([float(n) for n in line.strip().split(' ')])
This will should get your code working. What it does is convert all inputs into floats, and then convert balance and term into integers so that they can be used in your for loop. I tried the code on my PC, and it should be working.
See the exception traceback. The error is on line 11, and it basically says '5.5' is not an int. Which is correct - It's a float (a decimal).
Line 11 is currently:
values.append([int(n) for n in line.strip().split(' ')])
Try:
values.append([float(n) for n in line.strip().split(' ')])
Your trying to call int() on a decimal value, or float in python. That's why it's not working.
try int('5.5') in your interactive shell(IDLE), and you get the same error.
Try this:
values.append([int(float(n)) for n in line.strip().split()])
This will do the job if you don't mind losing the precision of your values, as int will round them to a whole number, and if you don't mind them all being floats then just use float instead of int
Related
def bill_cal():
split_amount = bill_amount_list * (1-cashback_rate) / person_split_no
print(f"each person should pay {split_amount}.")
bill_amount = input("How much is the bill? You can enter multiple bills separated by comma.\n")
bill_amount_list = bill_amount.split(",")
cashback_rate = float(input("Is there any credit card cashback on the bills? 2% = 0.02\n"))
person_split_no = int(input("How many people are splitting the bill?"))
for bill in map(float, bill_amount_list):
bill_cal()
I am trying to cast float on each item obtained from bill_amount.split(","), and perform the bill_cal() function, but got below error:
How much is the bill? You can enter multiple bills separarted by comma.
100,200
Is there any credit card cashback on the bills? 2% = 0.02
.02
How many people are splitting the bill?2
Traceback (most recent call last):
File "main.py", line 10, in <module>
bill_cal()
File "main.py", line 2, in bill_cal
split_amount = bill_amount_list * (1-cashback_rate) / person_split_no
TypeError: can't multiply sequence by non-int of type 'float'
You are "multiplying" your bill_amount_list which is... well, a list. Sequences can be "multiplied" by int (meaning you will repeat the sequence), but not by float, hence your error.
Pass your bill to the function, and use it in the computation:
def bill_cal(amount):
split_amount = amount * (1-cashback_rate) / person_split_no
#...
for bill in map(float,bill_amount_list):
bill_cal(bill)
You need to call the function with a local variable.
Also it's good practice to check your input as well like this:
if item.isnumeric():
'call the function'
Working on trying to understand variables input strung together to get calculations done.
Checked on here for quite some time but could not find the answer specific to my problem or if I did I may not of been able to identify it. very new so any tips/advice/resources is incredibly appreciated. Below is the beginning of the code I was working on.
print('Hello there! Today we will be learning how to calculate your macros! ')
print(' We will start of by gathering some of your info valuable in the calculations.')
H = input('How tall are you in inches over the 5ft mark? ')
W = input('Now how much do you currently weight in pounds? ')
A = input('Now how many hours of activity would you say that you get per day? ')
c = sum((H + 105)*10+400)
d = sum (c / 4)
carbs = sum (d * 2)/4
Here is the error message I am receiving from this.
Traceback (most recent call last):
File "C:\Users\ironv\PycharmProjects\pythonProject\HelloWorld\venv\app.py", line 7, in
<module>
c = sum((H + 19)*10)
TypeError: can only concatenate str (not "int") to str
What is my formatting error?
The input function returns a string. You must convert it to an integer if you want to use it as one.
Along with this, the sum function only works on iterables. Integers are not iterable, so using the sum function on one would cause the program to raise an error.
Your fixed code would look like this:
H = int(input('How tall are you in inches over the 5ft mark? '))
W = int(input('Now how much do you currently weigh in pounds? '))
A = int(input('Now how many hours of activity would you say that you get per day? '))
c = (H + 105)*10+400
d = c / 4
carbs = d * 2/4
Since the input() will return you a String variable, your H will be a String type. You need to convert it to int type first before doing any arithmetic.
H = input('How tall are you in inches over the 5ft mark? ')
print(type(H)) # <class 'str'>
H_int = int(H)
print(type(H_int)) # <class 'int'>
I am trying to make a program that can find a definite integral but when i run it I get an error message that i can not figure out even after searching on several websites for the answer. This is my code:
class Intagrals:
def main(self):
Coefficient = input("Coefficeient: ")
Exponet = input("Exponet: ")
X_start = input("X_Start: ")
X_end = input("X_End: ")
self.equation_parts(Coefficient,Exponet,X_start,X_end)
'''
For main to always run: if __name__ == '__main__':
main()
'''
def equation_parts(self,coefficient,exponet,x_start,x_end): #x_start and x_end are the beggining and end valuse to be set for x in the intagral
exponet += 1 #adds one to exponet for equation to be solved correctly
a_over_n_plus_1_x = coefficient/exponet #creates terms before x
def math_of_intagral(self):
solve_for_x = self.a_over_n_plus_1_x * self.x_end
raise_to_power_end_x = solve_for_x ** self.exponet
if self.x_start != 0:
solve_for_start_x = self.a_over_n_plus_1_x * self.x_start
raise_to_power_start_x = solve_for_start_x ** self.exponet
return raise_to_power_end_x - raise_to_power_start_x
else:
return raise_to_power_end_x
intagrals = Intagrals()
Then it displays this error message after I enter some code:
> >>> intagrals.main()
Coefficeient: 1
Exponet: 2
X_Start: 0
X_End: 2
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
intagrals.main()
File "C:/Users/owner/AppData/Local/Programs/Python/Python36-32/intagrals.py", line 15, in main
self.equation_parts(Coefficient,Exponet,X_start,X_end)
File "C:/Users/owner/AppData/Local/Programs/Python/Python36-32/intagrals.py", line 22, in equation_parts
exponet += 1 #adds one to exponet for equation to be solved correctly
TypeError: must be str, not int
Can someone Please help?
Whenever you use the input function in python, it returns a string. To quote the docs (emphasis mine):
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
As you see from the docs, the input() function converts the input to a string and returns it. Thus, you cannot perform operations like += 1 on it as it is a string.
To convert a string to an int, you need to use the int() function. Thus, the line of code will be:
Exponet = int(input("Exponet: "))
This will fix your issue as the int() function will cast the string to an int and then you should be able to perform operations like += on them.
Side Note: Exponet is a wrong spelling, it is Exponent (note the extra n).
You are reading the Exponet from input and that is always a string, when you try to increment it with exponet += 1 it gives that error.
You should modify your input to get an integer ant not a string, so change this line
Exponet = input("Exponet: ")
to this
Exponet = int(input("Exponet: "))
if you use
something = input("Exponet: ")
python takes it always as string. So to convert it into integer using
something = int(input("Exponet: "))
Here when you input Exponet: 2, Python thinks it is a string but when you try to increment it fails to increment the integer value because of you input string.
Your code is missing self. before the a_over... variable that you set in the equation_parts method. Later, you're referring to this variables using self.a_... which causes the AttributeError to be thrown.
I am new to Python, so I apologize if this is a simple fix. I have been stuck on a Codeval problem (Happy Numbers) for quite some time and I am not sure what is going wrong.
Problem Description:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1, or it loops endlessly in a cycle which does not include 1.Those numbers for which this process ends in 1 are happy, while those that do not end in 1 are unhappy.
For example:
7 is a happy number (7->49->97->130->10->1)
22 is not a happy number (22->8->64->52->29->85->89->145->42->20->4->16->37->58->89 ...)
My test input and expected outcome:
1 --> 1
7 --> 1
22 --> 0
If the number is a happy number, print out 1. If not, print out 0.
Here is the full Traceback:
Traceback (most recent call last):
File "/happy_number.py", line 58, in <module>
happy_number_check("happy_numbers.txt")
File "/happy_number.py", line 55, in happy_number_check
happy_or_not(line)
File "/happy_number.py", line 33, in happy_or_not
i = int(i)
ValueError: invalid literal for int() with base 10: ''
Here is my code:
# test = 7
def happy_or_not(number):
number = str(number)
if number == 1:
print 1
else:
new_num = 0
for i in number:
i = int(i)
if i == " ":
continue
else:
new_num += i**2
if new_num == 10 or new_num == 10:
print 1
else:
try:
happy_or_not(new_num)
except RuntimeError:
print 0
# happy_or_not(test)
def happy_number_check(file):
f = open(file, 'r+')
for line in f:
if line == "":
continue
else:
happy_or_not(line)
happy_number_check("happy_numbers.txt")
What I have already tried:
Based on what I gathered from other similar questions, the issue may be that I am not able to convert a str into an int when I hit the line i = int(i). It is my understanding that I have to convert the str type into an int type before doing any math on it, yet it looks like that is where it is failing.
I tested the happy_or_not function by itself, and it does print out the value that I expect it to. It seems like to me that the issue comes when I try and call that happy_or_not function inside of the happy_number_check function, which is reading my txt file (containing a list of numbers to test). I must not be grasping a larger principle here, so any explanations would be helpful.
This is also my first real attempt at a recursive function and there probably is a better way to structure this, so any suggestions on how to change things up to be more effective is most welcome.
Thank you in advance!
Try changing happy_number_check like this (validate each line is an integer):
def happy_number_check(file):
with open(file, 'r+') as f: # Safer way to open a file. Will automatically close for you even if something goes wrong
for line in f:
if line.strip().isdigit():
happy_or_not(line.strip())
The strip() will also make it so that you can remove this code:
if i == " ":
continue
else:
By the way, you also have a bug in your logic. You are relying on a RuntimeError - a Stack Overflow interestingly enough :-) - to terminate a test. You should really keep track of what numbers have been tried, and if you try the same number again, return 0.
Don't click this link if you don't want a straight up solution to the problem, but if you do, here is an iterative solution: http://rosettacode.org/wiki/Happy_numbers#Python
I'm trying to create a program that asks for a name of a file, opens the file, and determines the maximum and minimum values in the files, and also computes the average of the numbers in the file. I want to print the max and min values, and return the average number of values in the file. The file has only one number per line, which consists of many different numbers top to bottom. Here is my program so far:
def summaryStats():
fileName = input("Enter the file name: ") #asking user for input of file
file = open(fileName)
highest = 1001
lowest = 0
sum = 0
for element in file:
if element.strip() > (lowest):
lowest = element
if element.strip() < (highest):
highest = element
sum += element
average = sum/(len(file))
print("the maximum number is ") + str(highest) + " ,and the minimum is " + str(lowest)
file.close()
return average
When I run my program, it is giving me this error:
summaryStats()
Enter the file name: myFile.txt
Traceback (most recent call last):
File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 8, in summaryStats
builtins.TypeError: unorderable types: str() > int()
I think I'm struggling determining which part to make a string. What do you guys think?
You are comparing two incompatible types str and int. You need a make sure you are comparing similar types. You may want to rewrite your for loop to include a call to make sure you are comparing two int values.
for element in file:
element_value = int(element.strip())
if element_value > (lowest):
lowest = element
if element_value < (highest):
highest = element_value
sum += element_value
average = sum/(len(file))
When python reads in files, it reads them in as type str for the whole line. You make the call to strip to remove surrounding white space and newline characters. You then need to parse the remaining str into the correct type (int) for comparison and manipulation.
You should read through your error messages, they are there to enlighten you on where and why your code failed to run. The error message traces where the error took place. the line
File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 8, in summaryStats
Tells you to examine line 8 which is the place for the error takes place.
The next line:
builtins.TypeError: unorderable types: str() > int()
Tells you what is going wrong. A quick search through the python docs locates the description of the error. An easy way to search for advice is to look in the documentation for the language and maybe search for the entire error message. It is likely you are not the first person with this problem and that there is probably a discussion and solution advice available to figure out your specific error.
Lines like these:
if element.strip() > (lowest):
Should probably be explicitly converting to a number. Currently you're comparing a str to and int. Converting using int will take whitespace into account, where int(' 1 ') is 1
if int(element.string()) > lowest:
Also, you could do this like so:
# Assuming test.txt is a file with a number on each line.
with open('test.txt') as f:
nums = [int(x) for x in f.readlines()]
print 'Max: {0}'.format(max(nums))
print 'Min: {0}'.format(min(nums))
print 'Average: {0}'.format(sum(nums) / float(len(nums)))
when you call open(filename), you are constructing a file object. You cannot iterate through this in a for loop.
If each value is on it's own line: after creating the file object, call:
lines = file.readlines()
Then loop through those lines and convert to int:
for line in lines:
value = int(line)