PDA

View Full Version : Inputs in Python



7raTEYdCql
January 10th, 2009, 04:27 PM
How do i take two inputs and assign it to two different variables. When the inputs are seperated by a ' ' space.

jimi_hendrix
January 10th, 2009, 04:44 PM
this might work (not tested due to lack of interperater)



buf = raw_input("enter two numbers")
buf.split()
a = buf[0]
b = buf[1]

pmasiar
January 10th, 2009, 05:30 PM
Correct, but way too many lines. 'Better' way:



a, b = raw_input("enter two numbers").split(' ')

nvteighen
January 10th, 2009, 06:24 PM
Correct, but way too many lines. 'Better' way:



a, b = raw_input("enter two numbers").split(' ')

Ok, but that's too subtle ;)

snova
January 10th, 2009, 07:59 PM
this might work (not tested due to lack of interperater)



buf = raw_input("enter two numbers")
buf.split()
a = buf[0]
b = buf[1]


No, it won't. The split() method of strings doesn't change the variable, it returns a list. So you'd end up with the first two characters in the string.

pmasiar's code is probably the simplest way.

jimi_hendrix
January 10th, 2009, 08:26 PM
told you i dont have an inteperater...

ghostdog74
January 11th, 2009, 04:38 AM
Probably alright IF the OP can ensure 2 inputs every time. If used for production, its better to provide error checking. The code will fail to assign to the variables if more than or less than 2 inputs are provided.

Greyed
January 11th, 2009, 06:55 AM
Correct, but way too many lines. 'Better' way:



a, b = raw_input("enter two numbers").split(' ')


What ghostdog74 said (eep, we agreed on something?)...



>>> a, b = raw_input("enter two numbers").split(' ')
enter two numbers1 2 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
On the other hand there is a way to combine the two.



nums = raw_input("Enter two numbers: ").split()
a, b = nums[0:2]


Huh, or if we're doing the Perl all-in-one-line thing..



a, b = raw_input("Enter two numbers: ").split()[0:2]

But I really dislike chaining things together like that.

Bachstelze
January 11th, 2009, 07:16 AM
a, b = raw_input("Enter two numbers: ").split()[:2]


I win. :D