Reputation: 59
I have written this line as a single line for loop:
p.x, p.y, p.z = [float(s) for s in input('Input X, Y, Z: ').split()]
It works fine. But for my own understanding, I tried to expand it as this:
p.x, p.y, p.z = input('Input X, Y, Z: ').split()
float(p.x)
float(p.y)
float(p.z)
But it throws error (TypeError: unsupported operand type(s) for -: 'str' and 'str'
) whenever I try to do operations on them.
Can someone explain to me what I've done wrong and correct it?
Thanks a lot!
Upvotes: 0
Views: 127
Reputation: 92471
As others have said, float()
doesn't change the values of its input, it returns new values. A quick fix is to map()
the float
function onto the split input.
class P:
pass
p = P()
p.x, p.y, p.z = map(float, input('Input X, Y, Z: ').split())
print(p.__dict__)
# Input X, Y, Z: 5.6 3.2 6.7
# {'x': 5.6, 'y': 3.2, 'z': 6.7}
You'll probably want to catch exceptions for bad input too.
Upvotes: 2