1

I need to take in input like the following:

Enter two floating point values: 54.99, 32.3

In one line, I want to take in both values and save them as a floating point number but I have been unable to. So far I have the following:

val1, val2 = input("Enter two floating point values: ").split(",")

In that same line, I want to cast them to floating point numbers. How can that be done?

I do not want to do this:

val1, val2 = input("Enter two floating point values: ").split(",")
val1 = float(val1)
val2 = float(val2)

2 Answers 2

3

I'm not sure whether if there is a better way, but you can do it with list comprehension in one line:

val1, val2 = [float(item) for item in input("Enter two floating point values: ").split(",")]

Another option that you can do is by using the map function:

val1, val2 = map(float(input("Enter two floating point values: ").split(","))

Note that in Python 3.x the second version returns a map object rather than a list.

Although, you can convert it to list by doing:

val1, val2 = list(map(float,input("Enter two floating point values: ").split(",")))
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, that's exactly what I was looking for.
@Hatefiend , Your'e welcome, I've added another option that you can do at the answer.
you don't need lambda in the map, you can just do: val1, val2 = map(float, raw_input("whatever").split(",")
This question is tagged with python-3.x and you are using raw_input.
@TheClonerx , Thanks for noticing, fixed that.
0

Easiest way to do this:

# taking two inputs at a time 
# Python program showing how to 
# multiple input using split

x, y = input("Enter a two value: ").split() 
print("Number of boys: ", x) 
print("Number of girls: ", y) 
print()

# hit enter and give two numbers(Floating or Int- keep a space in between numbers)

Enter a two value: 12.25 58.45
Number of boys:  12.25
Number of girls:  58.45

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.