2

In Java, one can write something like this:

Scanner scan = new Scanner(System.in);
x = scan.nextInt();
y = scan.nextDouble();

etc.

What is the equivalent of this in Python 3? The input is a list of space separated integers and I do not want to use the strip() method.

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
tinachou28
  • 33
  • 1
  • 1
  • 6
  • Possible duplicate of [User input and command line arguments](https://stackoverflow.com/questions/70797/user-input-and-command-line-arguments) – George Z. Feb 17 '19 at 12:46
  • [https://stackoverflow.com/questions/70797/user-input-and-command-line-arguments](https://stackoverflow.com/questions/70797/user-input-and-command-line-arguments) – Raahul Feb 17 '19 at 12:46

2 Answers2

2

Use the input() method:

x = int(input())
y = float(input())

If you're looking to take a list of space separated integers, and store them separately:

`input: 1 2 3 4`
ints = [int(x) for x in input().split()]
print(ints)
[1, 2, 3, 4]
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
1

After you get your input using "input" function you could do :

my_input = input("Enter your input:") 
# my_input = "1, 2" 
def generate_inputs(my_input):
     yield from (i for i in my_input.split())

inputs = generate_inputs(my_input)
x = int(next(inputs))
y = int(next(inputs)) # you could also cast to float if you want 

If you want less code :

scan = (int(i) for i in input().split())
x = next(scan)
y = next(scan)
kederrac
  • 16,819
  • 6
  • 32
  • 55