Hatefiend
Hatefiend

Reputation: 3596

Python3 - Multiple inputs

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)

Upvotes: 1

Views: 2496

Answers (2)

rra
rra

Reputation: 809

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

Upvotes: 0

omri_saadon
omri_saadon

Reputation: 10621

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(",")))

Upvotes: 3

Related Questions