when I run the program this has been popping up. could not convert string to float. I tried to look it up but I couldn't find anything.
here's the code:
f = open("ticket.txt",'r')
s=f.read()
lines=s.split("\n")
priceMax=0
priceMin=9999
total=0
for line in lines:
cols=line.split(" ")
price=(float)(cols[1])
total=total+price
if(price>priceMax):
priceMax=price
if(price<priceMin):
priceMin=price
f.close()
f=open("output.txt",'w')
f.write("*******************************************\n")
f.write(" TICKET REPORT\n")
f.write("*******************************************\n\n")
f.write("There are " + str(len(lines)) + " tickets in the database.\n\n")
f.write("Maximum Ticket price is $" + str(priceMax) + "\n")
f.write("Minimum Ticket price is $" + str(priceMin) + "\n")
f.write("Average Ticket price is $" + str(total / len(lines)) + "\n\n")
f.write("Thank you for using our ticket system!\n\n")
f.write("*******************************************\n")
f.close()
print("File Created sucessfully")
Yeah, indentation is important in Python. You must be consistent.
This "cast" (float) evaluates to, basically, the float() function, and then you call it, so that's not the problem. More canonical is f = float("123.45"). Now, this will throw a ValueError exception if there's an invalid number passed, so, you might want to catch this, so you can find out where the problem is. Along the lines of:
s = "123.baboom"
try:
f = float(s)
except ValueError as e:
print("Oh, no, got an exception:", e)
print("The offending string was: ", s)
What's the error that's shown?
I think the issue is that you have started the list with cols[1] instead of cols[0].
Also the indentation is wrong here.
for line in lines:
cols=line.split(" ")
price=(float)(cols[0])
total=total+price
if(price>priceMax):
priceMax=price
if(price<priceMin):
priceMin=price
Related
What I trying to do is picking random integers from a value, for example: 1:32 will be an input, I will split by the : and then select a random value. Then Selenium will select the dropdown based on what value is returned.
My code:
# SELECT
if register_parts[3] == "SELECT":
if register_parts[0] + '="' + register_parts[1] + '"' in self.driver.page_source:
_select_value = ""
if ":" in register_parts[2]:
_select_value = self.get_random_value_between(register_parts[2])
_select = Select(selenium_action)
_select.select_by_visible_text(_select_value)
self.write_to_debug_file("self.select_by_visible_text(" + _select_value + ") --> SELECT --> [ " + _select_value + " ]")
else:
_select_value = register_parts[2]
_select = Select(selenium_action)
_select.select_by_visible_text(_select_value)
self.write_to_debug_file("self.select_by_visible_text(" + _select_value + ") --> SELECT --> [ " + _select_value + " ]")
Additional function:
def get_random_value_between(self, input_values):
''' this function will return a random value between: x:x or 1:31 for example ... '''
parts = input_values.split(':')
return random.randrange(int(parts[0]), int(parts[1]))
The problem is on this line:
_select.select_by_visible_text(_select_value)
I'm getting the error:
argument of type 'int' is not iterable
From reading up, I think the issue lies in the fact I am doing:
if ":" in
I could be wrong. I'm not sure how to fix it. Any help on the issue would be appreciated. As far as I can see, the code should work, but I must be missing something. I have read a few threads on here regarding the error but it's still not sinking totally in.
If possible, cast _select_value as string before using _select.select_by_visible_text.
And recast as int values after the iteration.
I think this is correct. If the error is on if and not the else, then your passing an Int as an argument to a method that needs a text/str value.
Just try the following line:
_select.select_by_visible_text(str(_select_value))
I wrote a length converter with python,
here are the codes:
active = True
while active:
option = input('please choose:\na:centimetre to inch \nb:inch to centimetre:')
if option == "a":
centimetre = input('Please enter centimetre:')
centimetre= float (centimetre)
inch = centimetre / 2.54
print(str(centimetre) + ' centimetre equals' + str(inch) + ' inches')
elif option == "b":
inch = input('Please enter inch:')
inch = float ( inch )
centimetre = inch * 2.54
print(str(inch) + ' inch equals ' + str(centimetre) + ' centimetre')
else:
print("sorry you entered wrong option。please enter 'a'or'b': ")
continue
status = input('continue? yes/no :')
if status == 'no':
active = False
It's ok when these codes run with notepad++ and
http://www.pythontutor.com/
but when I try to use pycharm, it got error:
line 6, in <module>
centimetre= float (centimetre)
ValueError: could not convert string to float:
not sure where is the problems. Has anyone met this issue?
You could try checking if the input is able to be converted into a float, using try:.
And, also, if it's an issue with Python not recognizing commas as a decimal point, and maybe periods as a thousands separator, then you could check for if the number with commas and periods swapped (using the .replace() method).
An example of this is:
x = '2.3'
y = '3,4'
def isnumber(num):
try:
float(num)
return True
except ValueError:
try:
float(num.replace(',', 'A').replace('.', 'B').replace('A', '.').replace('B', ','))
return True
except ValueError:
return False
if isnumber(x):
print(f'The number {x} is valid.')
else:
print(f'The number {x} is not valid.')
print()
if isnumber(y):
print(f'The number {y} is valid.')
else:
print(f'The number {y} is not valid.')
You are probably using wrong decimal separator on input. Perhaps comma "," instead of full stop "."
You need to replace that or catch the error (or both together). I suggest:
try:
centimetre = float(centimetre.replace(',', '.'))
except ValueError:
print('Input is not a valid number or in invalid format!')
i tried days to fix it and have solved this issue
i created a brand new project in pycharm and put the code in a new file.
it works now
if you just copy and paste the code to existed pycharm project, it might not work
not sure why, but at least it's not my codes' fault and it works now.
Try this:
centimetre = float(input('Please enter centimetre:'))
Working on outputting text and variables to a .txt file through python. And it doesn't work.
f=open("Output.txt", "a")
f.write("Number Plate:", np ,"\n")
f.write("Valid:", valid ,"\n")
f.write("Speed:", speed ,"\n")
f.write("Ticket:", ticket ,"\n")
f.wrtie("Ticket Price:", ticketprice ,"\n")
f.write("\n")
f.close()
This is the error that is given when i run it.
f.write("Number Plate:", np ,"\n")
TypeError: write() takes exactly one argument (3 given)
Any help is greatly appreciated
Try using str.format.
Ex:
f=open("Output.txt", "a")
f.write("Number Plate: {0}".format(np))
f.write("Valid: {0}".format(valid ))
f.write("Speed: {0}".format(speed ))
f.write("Ticket: {0}".format(ticket ))
f.write("Ticket Price: {0}".format(ticketprice ))
f.write("\n")
f.close()
Note: f.write takes only a single argument, You are trying to pass 3("Number Plate:", np ,"\n")
You can try like this:
with open("Output.txt", "a") as f:
f.write("Number Plate:" + str(np) + "\n")
f.write("Valid:" + str(valid) + "\n")
f.write("Speed:" + str(speed) + "\n")
f.write("Ticket:" + str(ticket) + "\n")
f.write("Ticket Price:" + str(ticketprice) + "\n")
f.write("\n")
Explanation:
If you use with open.... there is no need to explicitly specify the f.close(). And also in f.write() using string concatenation + you can get the required one.
You can simply use str() function
The str() function is meant to return representations of values which
are fairly human-readable.
And your valid code will be like-
f=open("Output.txt", "a")
f.write("Number Plate:" + str(np) + "\n")
f.write("Valid:" + str(valid) + "\n")
f.write("Speed:" + str(speed) + "\n")
f.write("Ticket:" + str(ticket) + "\n")
f.wrtie("Ticket Price:" + str(ticketprice) + "\n")
f.write("\n")
f.close()
your code giving Error, TypeError: write() takes exactly one argument (3 given)
because-
write() method takes only 1 argument, but you are providing 3 argument
1) "Number Plate:" , 2) np and 3) "\n"
I'm brand new to Python, my apologies if this is a trivial question. Have been googling for hours unsuccessfully.
I have a code that takes latitudes/longitudes from an Excel file and returns addresses using an API.
If Excel cells contain wrong Lat/Longs, it returns IndexError. In that case it just stops execution even if the next row contains correct (geocodable) Lat/Longs. I tried using while True, but it just keeps writing the results excluding the part after Except.
E.g. Excel has the following columns/values:
Lat Long
38.872476 -77.062334
1 23.456789
38.873411 -77.060907
The 1st line has correct Lat/Long, the 2nd incorrect, the 3rd correct. In the output file it shows the address of the 1st row and says "N/A" for the 2nd row, but ignores the 3rd row and stops execution.
try:
for row in range(rows):
row+=1
latitude = float(sheet.row_values(row)[0])
longitude = float(sheet.row_values(row)[1])
reverse_geocode_result = gmaps.reverse_geocode((latitude, longitude))
out_file.write("(" + str(latitude) + ", " + str(longitude) + ") location: " + str(reverse_geocode_result[1]['formatted_address']) + "\n")
except IndexError:
out_file.write("N/A")
else:
out_file.write("(" + str(latitude) + ", " + str(longitude) + ") location: " + str(reverse_geocode_result[1]['formatted_address']) + "\n")
print "Done."
I think you want to stick your try inside your for loop.
for row in range(rows):
try:
# Get the values
except IndexError:
out_file.write("N/A")
else:
out_file.write(...)
print "Done."
That way if there is an error, you'll write "N/A", but then be able to continue to the next element in the range.
I'm making a simple mad libs program in python 3 where the user enters in nouns and pronouns and the program is supposed to print out the inputs from the user.
Here is my code:
print ("Welcome to Mad Libs. Please enter a word to fit in the empty space.")
proper_noun = input("One day _________ (Proper Noun)").lower()
ing_verb = input("Was __________ (Verb + ing) to the").lower()
noun1= input("to the _________ (Noun)").lower()
pronoun1 = input("On the way, _____________ (Pronoun)").lower()
noun2 = input("Saw a ________ (Noun).").lower
pronoun2 = input("This was a surprise so ________ (Pronoun)").lower()
verb2 = input("_________ (verb) quickly.").lower()
#Asks user to complete the mad libs
print ("One day " + proper_noun)
print ("Was " + ing_verb + " to the")
print (noun1 + ". " + "On the way,")
print (pronoun1 + " saw a " + noun2 + ".")
print ("This was a surprise")
print ("So " + pronoun2 + " " + verb2 + " quickly.")
Getting this error code: TypeError: Can't convert 'builtin_function_or_method' object to str implicitly
On this line:
print (pronoun1 + " saw a " + noun2 + ".")
Fairly new to python, so i'm not entirely sure what this error means and how to fix it, can somebody explain this error code to me please?
The issue is with the noun2 variable
noun2 = input("Saw a ________ (Noun).").lower
You are assigning the function .lower to it , not the result of calling it . You should call the function as .lower() -
noun2 = input("Saw a ________ (Noun).").lower()
For Future readers
when you get an issues such as - TypeError: Can't convert 'builtin_function_or_method' object to str implicitly - when trying to concatenate variables contain strings using + operator.
The issue basically is that one of the variables is actually a function/method, instead of actual string.
This (as in the case with OP) normally happens when you try to call some function on the string, but miss out the () syntax from it (as happened in the case of OP) -
name = name.lower #It should have been `name.lower()`
Without the () syntax, you would be simply assigning the function/method to the variable , and not the actual result of calling the function. To debug such issues you can check out the lines where you are assigning to the variables , used in the line throwing the error, and check if you missed out on calling any function.