Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing numbers in Python

Tags:

python

parsing

i want to take inputs like this 10 12

13 14

15 16

..

how to take this input , as two diffrent integers so that i can multiply them in python after every 10 and 12 there is newline

like image 517
Hick Avatar asked Jan 23 '23 13:01

Hick


1 Answers

I'm not sure I understood your problem very well, it seems you want to parse two int separated from a space.

In python you do:

s = raw_input('Insert 2 integers separated by a space: ')
a,b = [int(i) for i in s.split(' ')]
print a*b

Explanation:

s = raw_input('Insert 2 integers separated by a space: ')

raw_input takes everything you type (until you press enter) and returns it as a string, so:

>>> raw_input('Insert 2 integers separated by a space: ')
Insert 2 integers separated by a space: 10 12
'10 12'

In s you have now '10 12', the two int are separated by a space, we split the string at the space with

>>> s.split(' ')
['10', '12']

now you have a list of strings, you want to convert them in int, so:

>>> [int(i) for i in s.split(' ')]
[10, 12]

then you assign each member of the list to a variable (a and b) and then you do the product a*b

like image 152
Andrea Ambu Avatar answered Feb 03 '23 13:02

Andrea Ambu