Read two variables in a single line with Python

2019-01-24 06:58发布

I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables?

I'm looking for the equivalent of:

scanf("%d%d", &i, &j); // accepts "10 20\n"

One way I am able to achieve this is to use raw_input() and then split what was entered. Is there a more elegant way?

This is not for live use. Just for learning..

标签: python input
7条回答
男人必须洒脱
2楼-- · 2019-01-24 07:39

I am new at this stuff as well. Did a bit of research from the python.org website and a bit of hacking to get this to work. The raw_input function is back again, changed from input. This is what I came up with:

i,j = raw_input("Enter two values:  ").split
i = int(i)
j = int(j)

Granted, the code is not as elegant as the one-liners using C's scanf or C++'s cin. The Python code looks closer to Java (which employs an entirely different mechanism from C, C++ or Python) such that each variable needs to be dealt with separately.

In Python, the raw_input function gets characters off the console and concatenates them into a single String as its output. When just one variable is found on the left-hand-side of the assignment operator, the split function breaks this String into a list of String values .

In our case, one where we expect two variables, we can get values into them using a comma-separated list for their identifiers. String values then get assigned into the variables listed. If we want to do arithmetic with these values, we need to convert them into the numeric int (or float) data type using Python's built-in int or float function.

I know this posting is a reply to a very old posting and probably the knowledge has been out there as "common knowledge" for some time. However, I would have appreciated a posting such as this one rather than my having to spend a few hours of searching and hacking until I came up with what I felt was the most elegant solution that can be presented in a CS1 classroom.

查看更多
登录 后发表回答