Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read two variables in a single line with Python

Tags:

python

input

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..

like image 784
Alterlife Avatar asked Oct 19 '09 11:10

Alterlife


People also ask

How do you read two variables in one line Python?

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

How do you read two integers on the same line in Python?

One solution is to use raw_input() two times. Note that we don't have to explicitly specify split(' ') because split() uses any whitespace characters as a delimiter as default.

How do I print multiple variables in one line Python?

To print multiple variables in Python, use the print() function. The print(*objects) is a built-in Python function that takes the *objects as multiple arguments to print each argument separated by a space.


2 Answers

No, the usual way is raw_input().split()

In your case you might use map(int, raw_input().split()) if you want them to be integers rather than strings

Don't use input() for that. Consider what happens if the user enters

import os;os.system('do something bad')

like image 74
John La Rooy Avatar answered Oct 23 '22 06:10

John La Rooy


You can also read from sys.stdin

import sys

a,b = map(int,sys.stdin.readline().split())
like image 28
MAK Avatar answered Oct 23 '22 06:10

MAK