ValueError: could not convert string to float: '40.0,' - python

I'm trying to convert string in list into float without using join() map() enumerate() replace() these built-in function as assignment requirement. What else can I use to remove comma after the number?
Create an ordering system for customer to buy something that uploaded by admin.
This is the whole purchasing function that i do:
def place_order():
try:
fileHandler= open('groceries_list.txt','r')
except:
print('File cannot be opened.')
exit()
gro=fileHandler.readlines()
if len(gro) == 0:
print("Sorry! There are no groceries in our store yet.")
else:
repeat = True
while repeat == True:
try:
fo= open('groceries_list.txt')
fr= fo.readlines()
except:
print('File cannot be read.')
order_list=[]
total=0
onp=[]
view_gro()
product= input('Please enter groceries name you want to purchase: ').upper()
for line in fr:
line=line.rstrip()
if not product in line:
continue
print(line)
line=line.split()
print('The price for',product,'is RM',(line[3]))
######################need to convert line[3] in list to float
line[3]=float(line[3])
total=total+line[3]
order_list.append(product)
print('Product successful added to you shopping cart!')
again= input('Do you need anything else? YES for continue or NO for quit.').upper()
if again == 'YES':
continue
elif again == 'NO':
print("Here's your shopping cart item")
print(order_list)
print('Total amount for your purchasing is RM',total)
try:
while True:
pay=int(input('You pay: RM '))
balance= total-pay
if balance == 0:
print('Pay successfully! Thanks for your purchasing')
fw= open('order_list_c.txt','w')
fw.write(order_list)
fw.write('\n')
fw.close()
repeat=False
#break
else:
print('Pay unsuccessfully! Please try again.')
continue
except ValueError:
print('Please enter numeric proper amount.')
continue
else:
print('Please enter YES or NO')
print('==============================')
continue
# else:
# print('Product not in list.')
# continue
#else:
# print('No products found. Try again.')
# continue
fo.close()
fileHandler.close()
This is the part Im talking about.
for line in fr:
line=line.rstrip()
if not product in line:
continue
print(line)
line=line.split()
print('The price for',product,'is RM',(line[3]))
######## need to convert line[3] in list to float but contains comma ######
line[3]=float(line[3])
total=total+line[3]
This is error showed
line[3]=float(line[3])
ValueError: could not convert
string to float: '40.0,'
This is the list:
['FOOD', 'vege', 2022, 40.0, 'fresh']

Assuming you get from the file, a str: "['FOOD', 'vege', 2022, 40.0, 'fresh']"
then when you line=line.split() it will split on the spaces, so your array of strings will look like:
[ "['FOOD',", "'vege',", "2022,", "40.0,", "'fresh']"]
and then float() chokes on the unexpected ,.
Try to split(", "), but keep in mind, your 0th (first) and -1th (last) elements will have an extra [ or ] in their strings.

Use ast.literal_eval() to parse the line, rather than using split() and float().
import ast
for line in fr:
line_list = ast.literal_eval(line)
if product not in line_list:
continue
price = line_list[3]
print('The price for',product,'is RM',price)

Related

In Python, How can I create a while loop using input + 'filename'

I am wanting to create a loop for my book reader so that when the user inputs a number other than 1-10, an error message comes up, and when they press 0 the program quits. However, an error message appears saying FileNotFoundError: No such file or directory: '11.txt'(etc)
import time
option = str(input('Which Book would you like to read? (1-10): '))
while option !=0:
number_of_words = 0
f=open(option + '.txt', encoding='utf-8')
file_contents=f.read()
lines = file_contents.split()
number_of_words += len(lines)
print('Word Count:',number_of_words)
time.sleep(2)
f=open(option + '.txt', encoding='utf-8')
for line in f:
print(line)
time.sleep(0)
else:
print("404 file not found")
print()
option=str(input('Which Book would you like to read?(1-10):'))
print("Goodbye")
Try this:
import time
while True:
try: # Wrap the input in a try except and try to convert it directly to an integer.
option=int(input('Which Book would you like to read? (1-10): '))
except:
print("Please only enter a number.")
continue
if option == 0:
print("Goodbye")
break
if option > 10:
print("Invalid book entered, try again, must be between 1 and 10.")
continue
with open(str(option) + '.txt', encoding='utf-8') as f: # Use a context manager to open files, it will make sure your files are closed after opening
file_contents=f.read()
number_of_words = len(file_contents.split())
print('Word Count:',number_of_words)
time.sleep(2)
for line in file_contents:
print(line)
Results:
Which Book would you like to read? (1-10): few
Please only enter a number.
Which Book would you like to read? (1-10): 121
Invalid book entered, try again, must be between 1 and 10.
Which Book would you like to read? (1-10): 0
Goodbye

Python program to input data of students with their marks in a text file and another file containing the students with decreasing percentage

import pickle
while True:
print(''' 1. Create Binary File.
2. Display the File.
3. Details of a particular student
4. Overall Topper and Subject-wise Topper
5. Students with percentage in decreasing order''')
a=int(input('choose a command (1-8): '))
if a==1:
f=open('student.dat','wb')
o=open('suiuii.dat','wb')
x=int(input('How many student: '))
for i in range(x):
name=input('Name: ')
phy=int(input('Physics Mark: '))
chem=int(input('Chemistry Mark: '))
cs=int(input('CS Mark: '))
maths=int(input('Maths Mark: '))
english=int(input('English Mark: '))
total=phy+chem+cs+maths+english
per=(total / 500) * 100
if total<45:
grade="FAIL"
if total>=45:
grade="D"
if total>60:
grade="C"
if total>75:
grade="B"
if total>90:
grade="A"
t=[name,phy,chem,cs,maths,english,total,str(per)+"%",grade]
g=[str(per)+"%"]
pickle.dump(g,o)
pickle.dump(t,f)
f.close()
elif a==2:
f=open('student.dat','rb')
try:
while True:
p=pickle.load(f)
print(p)
except:
f.close()
elif a==3:
f=open('student.dat','rb')
find=input('Name: ')
while True:
p=pickle.load(f)
if p[0]==find:
print(p)
break
f.close()
I tried to solve the 4th and 5th choice which is getting the overall topper and subject-wise topper in a text file and printing the students with their decreasing percentage in another file but I didn't get it.
Please help me to solve that
pickle is not the easiest way to do this but for training purpose you can find max and sort using the same lambda function:
elif a==4:
f=open('student.dat','rb')
all_students = []
while True:
try:
all_students.append(pickle.load(f))
except EOFError:
break
# getting student with highest total (index 6) and printing their name (index 0)
print(max(all_students, key=lambda x: x[6])[0])
f.close()
elif a==5:
f=open('student.dat','rb')
all_students = []
while True:
try:
all_students.append(pickle.load(f))
except EOFError:
break
# sorting all students according to their grade
all_students.sort(key=lambda x: x[6], reverse=True)
for stud in all_students:
# print name and percentage:
print(f"{stud[0]}: {stud[7]}")
f.close()

Key-value pairs not functioning of a dictionary when storing the dictionary in a binary file, why?

The purpose of the code is to assign roll no to name, both stored in a dictionary as key-value pairs. The search function should for a given roll no return the corresponding name, but it doesn't, and I have no clue why.
This is the faulty code:
import pickle
f=open('atextfile.dat','wb')
d={}
while True:
name=input('enter name: ')
rollno=int(input('enter rollno: '))
d[rollno]=name
con=input('Do you want to continue?(y/n): ')
if con=='n':
break
print(d)
pickle.dump(d,f)
f.close()
def search():
f=open('atextfile.dat','rb')
r=pickle.load(f)
roll=int(input('what roll no number?: '))
try:
n=d[rollno]
print('name is',n)
except:
print('rollno not found :/')
f.close()
search()
This is the anomalous output I am getting:
change d[rollno] to d[roll] as you used the variable roll for loading the contents of the file
import pickle
f=open('atextfile.dat','wb')
d={}
while True:
name=input('enter name: ')
rollno=int(input('enter rollno: '))
d[rollno]=name
con=input('Do you want to continue?(y/n): ')
if con=='n':
break
print(d)
pickle.dump(d,f)
f.close()
def search():
f=open('atextfile.dat','rb')
r=pickle.load(f)
roll=int(input('what roll no number?: '))
try:
n=d[roll] # this was the fault
print('name is',n)
except:
print('rollno not found :/')
f.close()
search()

How can i remove " " and . from a data in a list

So i have this college python project that asks me to make a program to manage an inventory, my question basically is that whenever I try to convert the price and the quantity again to floats this exception rase, so how can I convert them so I can make further process on them?
note that I tried to use .strip but it didn't work
this is the error:
float_price = float(i)
ValueError: could not convert string to float: '.'
this is the code that I have issues with:
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
float_price = float(i)
price += float_price
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()
this is the code to add data to the file:
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n' + make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to import the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+ '\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
as error message indicates '.' is string and it cannot be converted to float so raises error.. it depends what you want to do with such situation you can use try except as.
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
try:
float_price = float(i)
price += float_price
except ValueError as e:
print('Value Error')
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()

Line breaks with lists

I have a working script but it does not work the way I want it to:
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
myInput = input()
if myInput == "nothing":
print('There are ' + str(len(basket)) + ' items in the basket: '+ str(basket))
break
else:
basket.append(myInput)
print('Okay, what else?')
The final line is supposed to look like this:
There are 3 items in the basket:
Item 1: a sandwich
Item 2: two cans of Dr Pepper
Item 3: some napkins
Any suggestions?
Use enumerate with a start index of 1 and str.format:
while True:
myInput = input()
if myInput == "nothing":
print('There are {} items in the basket: '.format(len(basket)))
for ind, item in enumerate(basket,1):
print("Item{}: {} ".format(ind,item))
break
else:
basket.append(myInput)
print('Okay, what else?')
You can also use a list comprehension and iter without needing a while loop, it will keep looping until the user enters the sentinel value "nothing":
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = [ line for line in iter(lambda:input("Please enter an item to add"), "nothing")]
print('There are {} items in the basket: '.format(len(basket)))
for ind,item in enumerate(basket,1):
print("Item{}: {} ".format(ind,item))
I think its better to separate collecting input and printing the results as follows:
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
myInput = input()
if myInput == "nothing":
break
else:
basket.append(myInput)
print('Okay, what else?')
print('There are ' + str(len(basket)) + ' items in the basket: ')
for i,item in enumerate(basket):
print("Item {}: {}".format(i+1, item))
An empty string (just a carriage return) will still be considered an item, even though nothing will be there, which will cause an incorrect # of items in your basket and an empty Item line to be printed. Consider catching that and ignoring it, or potentially making it equivalent to "nothing" in the second if statement as part of the break condition.
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
myInput = input()
if myInput == "":
continue
if myInput == "nothing":
print('There are ' + str(len(basket)) + ' items in the basket:')
for itemno, item in enumerate(basket):
print("Item {0}: {1}".format(itemno+1,item))
break
else:
basket.append(myInput)
print('Okay, what else?')

Categories

Resources