zingy
zingy

Reputation: 811

input 2 variables separated by a comma in a single line

Is it possible to input 2 numbers int or float separated by a comma in a single line?

Say after the program runs it would ask the user to Enter a range: then the user would input 2,3. So the variable range is [2,3]. As far as I know range_choice.split() is the only way.

Upvotes: 4

Views: 21920

Answers (6)

Saptarshi das
Saptarshi das

Reputation: 439

You can use:

for int

a,b = map(int,input().split(','))

or

a,b = [int(i) for i in input().split(',')]

for float

a,b = map(float,input().split(','))

Syntax:

var1 sep var2 sep ... sep varn = map(type, input().split('sep'))

or

var1 sep var2 sep ... sep varn = [type(var) for var in input().split('sep')]

for string

a, b = input().split(',')

Upvotes: 0

Mitkumar Patel
Mitkumar Patel

Reputation: 91

In python3 you can directly use input() method instead of raw_input()

var1,var2 = input().split(',')

Upvotes: 0

phihag
phihag

Reputation: 287825

num1,num2 = map(float, raw_input('Enter a range: ').split(','))

Alternatively, if you want to allow commas in the second value, use partition instead of split:

s1,_,s2 = raw_input('Enter a range: ').partition(',')

In this case, you'll have to convert the two strings to numbers by yourself.

Upvotes: 4

senderle
senderle

Reputation: 150977

It's my understanding that ast.literal_eval is safe:

>>> x, y = ast.literal_eval(raw_input('Enter a range: '))
Enter a range: 5, 6
>>> x, y
(5, 6)

Upvotes: 0

josh
josh

Reputation: 1554

     x,y = input("Enter range: ")

If you want them as numbers it's best not to use raw_input.

Upvotes: 0

Michał Šrajer
Michał Šrajer

Reputation: 31182

num1, num2 = raw_input('Enter a range: ').split(',')

Upvotes: 0

Related Questions