Reputation: 13497
I read similar threads with my error and could not find the solution. In most other threads it seemed that people were inputting data incorrectly, but as you can see I am inputting the values with the correct typology. I can't seem to find what else I could be missing. Any ideas?
def main():
a, b, c, d, e, f = float(input("Enter a, b, c, d, e, f: "))
x = ((e * d) - (b * f))/ (
(a * d) - (b * c) )
y = ((a * f) - (e * c)) / (
(a * d) - (b * c) )
print("x is %f and y is %f" % (x,y))
if __name__ == "__main__":
main()
Error message:
>>>Enter a, b, c, d, e, f: 9.0, 4.0, 3.0, -5.0, -6.0, -21.0
ValueError: could not convert string to float: '9.0, 4.0, 3.0, -5.0, -6.0, -21.0'
Upvotes: 0
Views: 3739
Reputation: 304205
If you ensure the decimal point is always included
from ast import literal_eval
a, b, c, d, e, f = literal_eval(input("Enter a, b, c, d, e, f: "))
If the decimal point is missing, the corresponding variable will be an int instead of a float
Upvotes: 1
Reputation: 76715
The problem is that a series of float values, separated by commas, cannot be converted to a single float
.
Either ask for each float individually, or split up the input string on commas and loop through them converting.
I recommend asking for each float individually. Write a function input_float()
that takes input from the user, attempts to convert to float, and tells the user if there was a problem; it can have a loop that keeps looping until the user successfully enters a float value.
You might want to make your input_float()
function accept a string to display as a prompt, another string to show on error, and a function to validate the input. So if the user must enter a float value between 0 and 100, you could make a validation function that performed this check.
Once you have written a flexible input_float()
function, you can use it over and over again in your program.
Upvotes: 0
Reputation: 23231
the float()
function tries to convert the entire string to a single float. Technically this would work:
a, b, c, d, e, f = [float(number) for number in input("Enter a, b, c, d, e, f: ").split(', ')]
But keep in mind there's no error handling if it doesn't
Upvotes: 2