Python - For every value in text file? - python

With the code I am writing, I have split a text file up using commas, and now for each value in there, I want to make it an integer. I have tried splitting the text file and then turning it into an integer but that would not work. Is there any way of saying for all values in a file, do a certain thing? Also, the amount of values isn't concrete, it depends on the user of the programme (it is a 'shopping list' programme.
My current code:
TotalCOSTS=open("TotalCOSTS.txt","r")
Prices=TotalCOSTS.read()
print(Prices)
Prices.strip().split(",")
IntPrices=int(NewPrices)
print(len(IntPrices))
if len(IntPrices)==1:
print("Your total cost is: "+IntPrices +" Pounds")
elif len(IntPrices)>1:
FinalTotal = sum([int(num) for num in IntPrices.split(",")])
print("Your total cost is: "+ FinalTotal +" Pounds")
Prices is the file that the values are contained in, so I've stripped it of whitespace and then split it. That is where I need to continue on from.
Thank you xx

results = [int(i) for i in results]
python 3 you can do:
results = list(map(int, results))

NewPrices isn't defined in your code example
split() returns a list
The most straight-forward way to accomplish what you are trying to do is the following:
total = sum([int(x) for x in TotalCOSTS.read().split(',') if x.isdigit() == True])
But this makes some super-simplifying assumptions which won't be accurate all of the time. For example, if something costs $2.99, int() will cast this to 3. Overall, you want to consider the price in terms of cents (idk which currency you are using, but in USD, 100 cents = 1 dollar) so that $2.99 = 299 cents.
So really, you want something like this:
total = sum([float(x)*100 for x in TotalCOSTS.read().split(',') if x.isnumeric() == True])/100

Related

TypeError: ">” not supported between instances of "str' and int‘

I know I’m missing something with this code. Can someone please help me? I’m new to coding and I’ve struggling with this all day. I don’t want to keep emailing my instructor so maybe I can get help from here. I’m trying to get it to run through the if statements with user input and then calculate the amount but I don’t know what I’m missing.enter image description here
You should post code you're asking about as text in your question.
Going over your code with some comments:
print("Welcome") # no issue here, although Python default is single quotes, so 'Welcome'
print = input("Please enter company name:")
After that last line, print is a variable that has been assigned whatever text was entered by the user. (even if that text consists of digits, it's still going to be a text)
A command like print("You total cost is:") will no longer work at this point, because print is no longer the name of a function, since you redefined it.
num = input("Please enter number of fiber cables requested:")
This is OK, but again, num has a text value. '123' is not the same as 123. You need to convert text into numbers to work with numbers, using something like int(num) or float(num).
print("You total cost is:")
The line is fine, but won't work, since you redefined print.
if num > 500:
cost = .5
This won't work until you turn num into a number, for example:
if int(num) > 500:
...
Or:
num = int(num)
if num > 500:
...
Also, note that the default indentation depth for Python is 4 spaces. You would do well to start using that yourself. Your code will work if you don't, but others you have to work with (including future you) will thank you for using standards.
Finally:
print = ("Total cost:, num")
Not sure what you're trying to do here. But assiging to print doesn't print anything. And the value you're assigning is just the string 'Total cost:, num'. If you want to include the value of a variable in a string, you could use an f-string:
print(f"Total cost: {num}")
Or print them like this:
print("Total cost:", num) # there will be a space between printed values

Extract numbers from a string in python without the use of isdigit or re. tools

Let's say I have a string of integers generated by user input, where each integer is separated by a space (Code below for example)...
How can I search through that string and store each integer separately for use later on in the program? (I.E. Assigning each integer to its own variable) I can't use isdigit and cant use re tools, and I can't store the ints into a list.
userEntry = input("Please enter a Fahrenheit temperature: ")
for i in range(4):
userEntry += " " + input("Please enter another fahrenheit:")
Things I AM allowed to use: string methods, index find/search methods, for loops, if statements, while loops.
Something like this will parse the string into space-separated strings, using slices... (I notice the first answer came in while I was working on this, but this is slightly different, so...)
def extractor(mystr):
start = 0
for a in range(len(mystr)):
if mystr[a] == ' ' or mystr[a] == len(mystr) - 1:
temp = mystr[start:a]
print(temp)
start = a + 1
This is more like a C approach, very un-Pythonic, but standard programming fare. If you will only ever have 5 user entries, this is perhaps manageable. If you can't use a list of those variables, or if you have an unknown number of user entries, or if you have to check to make sure the user actually entered a digit and not a letter, then more work is required, but that's the basic C-string parser. Useful to know if you ever want to dive into Python internals I suppose.
If you need to convert each extracted string to an int, and exceptions are allowed, place this inside the if statement to check for type correctness:
try:
myvar1 = int(temp)
except ValueError:
print("Not an int")
Note that if you absolutely cannot use lists, (*or exec as in the above answer) then the only likely option is to keep slicing off the end of the string, i.e you'd have to do something like the following at the end of each if statement, then write that for loop out 4 more times, changing the variable name each time manually.
mystr = mystr[start:len(mystr)]
break
This will of course not work if you have a variable number of user entries. And is incredibly tedious... I suspect the instructor may have intended something different. Note that the real-world process for all that is just:
result = [int(x) for x in mystr.split(' ') if x.isdigit()]
I am not sure what your use case is, and I can not think of a way where you can assign the numbers to variable in a loop, which is what you have to do if you are not allowed to use a loop. The only way I can think of is exec and I do not feel that is allowed for your task. Regardless, I am posting the answer, in case it is usable:
last_space_index = 0
characters_checked = 0
var_num = 1
userEntry = "12.8 -15.8 125.9 0 -40.0"
for character in userEntry:
characters_checked += 1
if character == ' ':
number = float(userEntry[last_space_index:characters_checked])
var_name = 'var'+str(var_num)
var_num += 1
expression = var_name + ' = number'
# expression becomes 'var1 = number'
exec(expression)
last_space_index = characters_checked
last_number = float(userEntry[last_space_index:])
var_name = 'var'+str(var_num)
expression = var_name + ' = last_number'
exec(expression)
# if you know the number of variables you are going to get
print(var1, var2, var3, var4, var5)
# else:
# for i in range(1,var_num+1):
# var_name = 'var'+str(i)
# command = 'print('+var_name+')'
# exec(command)
Output:
>>> 12.8 -15.8 125.9 0 -40.0
You can replace print with whatever you actually want to do.
And this is completely futile if you are allowed to use dictionary, sets or tuple.

How do I manipulate data in a list that has been read in from a file using Python 2.x?

I am trying to create a program that will tally the cost of ingredients within a recipe and return a total cost for said recipe. I am teaching myself Python and have set this as a personal, but practical, challenge. However, I have hit a wall. Hard.
My idea was to read a file into a list. Multiply the ingredient within the list by the comma separated numeral. Add it all together, and return a single float for the overall cost.
#Phase 1 - MASTER INGREDIENTS LIST
flour_5lb = 2.5
sugar_4lb = 2.0
butter_lb = 3.0
eggs_doz = 3.0
#PHASE 2 - COST PER UNIT CONVERSION
flour_cup = flour_5lb*(1.0/20)
sugar_cup = sugar_4lb*(1.0/8)
butter_Tbsp = butter_lb*(1.0/32)
eggs_each = eggs_doz*(1.0/12)
#PHASE THREE - RECIPE ASSESSMENT
def main():
fileObject = open("filname.txt", "r")
fileLines = fileObject.readlines()
fileObject.close()
for line in fileLines:
print line
print "\n"
if __name__ == "__main__":
main()
The for line in fileLines: statement prints the following:
flour_cup, .5
milk_cup, .4
eggs_each, 3
butter_Tbsp, 3
Press any key to continue . . .
If I understand you correctly, you have to parse your file.
For this you need to know the format in which the ingredients are being stored. Since this program is for your personal use you may just choose the most simple.
So let's assume you have your ingredients in CSV format:
sugar 10g
flour 20g
...
Then you can use pythons buildin function split and iteration to obtain a list of list [['sugar', '10g'], ['flour', '10g'], ...].
Getting the amounts into python floats is a little tricky, since we haave to concern ourselves with the units.
Again - choose a fixed set of units to make your life a little easier.
Then use the in statement or the builtin function which checks if a given string has a certain suffix. (I will leave it to you to find this function.)
Then the hard part is done. Hope I could help without giving too much away.
Part of your difficulty is knowing how to split your input on the comma -- use split(). Another problem is converting the string to a float -- use float().
Your last problem is mapping input strings to values. You could write a function that maps strings to costs:
if item == "milk_cup":
return milk_cup
if item == "flour_cup":
return flour_cup
...
...but the better way (DRY) to do it is to use a dictionary.
In my sample below I've used dict() to make the dictionary as then I don't have to quote every string.
Here's a sample:
#!/usr/bin/python
pricelist = dict(
flour_cup=1.0,
milk_cup=0.4,
)
input = ["flour_cup, 0.5", "milk_cup, 0.4"]
total = 0
for line in input:
item, qty = line.split(",")
item = item.strip()
qty = float(qty)
if item in pricelist:
cost = qty * pricelist[item]
print "%s: %.02f\n" % (item, cost)
total += cost
else:
print "I don't know what '%s' is" % item
print "Total: %.02f" % total

How to find the sum of values in a column from a text file if matching certain criteria

I'm having some trouble trying add certain values in a column from a text file together. My text file looks like:
e320,2/3/5,6661,c120,A,6661
e420,6/5/3,16916,c849,A,24323
e432,6/5/3,6962,c8429,A,4324
e430,6/5/3,4322,c8491,A,4322
e32042,2/3/5,13220,c1120,A,13220
e4202,6/5/3,4232,c8419,E,4232
I would like to find the sum of the last column's values, provided in the array the third column (final total) is equal to the last column. (amount paid.). The total of all the last column's values should only be found if the fifth column's (status) equals 'E' and finaltotal == amountpaid.
My code so far for this is:
data = open("paintingJobs.txt", "r")
info=data.readlines()
data.close
totalrev=0
for li in info:
status=li.split(",")[4]
finaltotal=int(li.split(",")[2])
amountpaid=int(li.split(",")[5])
if amountpaid == finaltotal:
revenue=True
if status == "A" and revenue == True:
totalamountpaid = li.split(",")[5]
total = (sum(totalamountpaid))
print("The total revenue is")
print(total)
My desired output would be:
The total revenue is
28435
The total should equal 28435 as 6661+4322+13220+4232=28435 (the sum of the total revenues where status equals 'A' and finaltotal=amountpaid.)
I keep receiving a "TypeError: unsupported operand type(s) for +: 'int' and 'str'". I'm using Python 3.4.3 and a complete newbie to Python. Any help would be much appreciated.
Try this.
total = (sum(totalamountpaid))
to
total = (sum(map(int,totalamountpaid.split(','))))
Split every number from the string map converting the string to int. Then sum them up.
...assuming that the third column should be equal to 'E':
data = open("test.txt", "r")
info=data.readlines()
s = sum([int(li.split(',')[5]) for li in info if li.split(",")[4]=="E" and int(li.split(",")[2])==int(li.split(",")[5])])
print("The total revenue is")
print(s)
Tested. Returns 24113, i.e. 6661+13220+4232.
You are fetching strings from your text file. That means you first need to cast the values to appropriate data type (from strings) before adding them up.
Try changing this line total = (sum(totalamountpaid)) to total = (sum(Decimal(totalamountpaid))) or total = (sum(float(totalamountpaid)))
Just need to make use of the 'totalrev' variable and add up 'amountpaid' every time the 'for loop' executed, and only adding the numbers determined by your criteria. At the end you just call it in your print statement. I removed two lines of codes you didn't need after the small change.
data = open("paintingJobs.txt", "r")
info=data.readlines()
data.close()
totalrev=0
for li in info:
status=(li.split(",")[4])
finaltotal=int(li.split(",")[2])
amountpaid=int(li.split(",")[5])
if amountpaid == finaltotal:
totalrev += amountpaid
revenue=True
if status == "E" and revenue == True:
print("The total revenue is: " + str(totalrev))
This works with the data you provided, I get 28435 which is what you were looking for
It is because at this line,
total = (sum(totalamountpaid))
the sum function is applied to a string
So using your example data, you are effective asking python to execute this
sum("4322")
which is equivalent to
0 + "4" + "3" + "2" + "2"
Of course you cannot add string to a numeric value 0. Hence the error message.
Actually there are a few many issues with your code. I think you need to make these changes to make it work. See comments (words after #) for explanation. Not tested.
data = open("paintingJobs.txt", "r")
info=data.readlines()
data.close() ## Need the '()' to call the function
totalrev=0
for li in info:
status=li.split(",")[4]
finaltotal=int(li.split(",")[2])
amountpaid=int(li.split(",")[5])
if amountpaid == finaltotal:
revenue=True
if status == "A" and revenue == True:
totalamountpaid = li.split(",")[5]
### Assuming you actually want to accumulate the sum in variable `totalrev`
totalrev += int(totalamountpaid) ### you need to convert totalamountpaid to a numeric value, and add to the running total `totalrev`
print("The total revenue is")
print(totalrev)

how to calculate percentage in python

This is my program
print" Welcome to NLC Boys Hr. Sec. School "
a=input("\nEnter the Tamil marks :")
b=input("\nEnter the English marks :")
c=input("\nEnter the Maths marks :")
d=input("\nEnter the Science marks :")
e=input("\nEnter the Social science marks :")
tota=a+b+c+d+e
print"Total is: ", tota
per=float(tota)*(100/500)
print "Percentage is: ",per
Result
Welcome to NLC Boys Hr. Sec. School
Enter the Tamil marks :78
Enter the English marks :98
Enter the Maths marks :56
Enter the Science marks :65
Enter the Social science marks :78 Total is: 375 Percentage is: 0.0
However, the percentage result is 0. How do I calculate the percentage correctly in Python?
I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"
Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...
I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.
#!/usr/local/bin/python2.7
marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list
#here we populate the dictionary with the marks for every subject
for subject in subjects:
marks[subject] = input("Enter the " + subject + " marks: ")
#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)
print ("The total is " + str(total) + " and the average is " + str(average))
Here you can test the code and experiment with it.
You're performing an integer division. Append a .0 to the number literals:
per=float(tota)*(100.0/500.0)
In Python 2.7 the division 100/500==0.
As pointed out by #unwind, the float() call is superfluous since a multiplication/division by a float returns a float:
per= tota*100.0 / 500
This is because (100/500) is an integer expression yielding 0.
Try
per = 100.0 * tota / 500
there's no need for the float() call, since using a floating-point literal (100.0) will make the entire expression floating-point anyway.
Percent calculation that worked for me:
(new_num - old_num) / old_num * 100.0
marks = raw_input('Enter your Obtain marks:')
outof = raw_input('Enter Out of marks:')
marks = int(marks)
outof = int(outof)
per = marks*100/outof
print 'Your Percentage is:'+str(per)
Note : raw_input() function is used to take input from console and its return string formatted value. So we need to convert into integer otherwise it give error of conversion.
I know I am late, but if you want to know the easiest way, you could do a code like this:
number = 100
right_questions = 1
control = 100
c = control / number
cc = right_questions * c
print float(cc)
You can change up the number score, and right_questions. It will tell you the percent.
def percentage_match(mainvalue,comparevalue):
if mainvalue >= comparevalue:
matched_less = mainvalue - comparevalue
no_percentage_matched = 100 - matched_less*100.0/mainvalue
no_percentage_matched = str(no_percentage_matched) + ' %'
return no_percentage_matched
else:
print('please checkout your value')
print percentage_match(100,10)
Ans = 10.0 %
#Just begining my coding career with Python
#here's what i wrote its simple
print("\nEnter your marks to calculate percentage")
a=float(input("\nEnter your English marks"))
b=float(input("\nEnter your Mathematics marks"))
c=float(input("\nEnter your Science marks"))
d=float(input("\nEnter your Computer Science marks"))
e=float(input("\nEnter your History marks"))
tot=a+b+c+d+e
print("\nTotal marks obtained",tot)
per=float(tot/500)*100
print("Percentage",per)
You can try the below function using part == total marks out of whole == 500.
def percentage(part, whole):
try:
if part == 0:
percentage = 0
else:
percentage = 100 * float(part) / float(whole)
return "{:.0f}".format(percentage)
except Exception as e:
percentage = 100
return "{:.0f}".format(percentage)

Categories