tinachou28
tinachou28

Reputation: 33

Equivalent of java.util.Scanner in python

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.

Upvotes: 2

Views: 12783

Answers (2)

kederrac
kederrac

Reputation: 17322

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)

Upvotes: 1

AlanK
AlanK

Reputation: 9853

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]

Upvotes: 2

Related Questions