4

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

zoul
  • 102,279
  • 44
  • 260
  • 354
Hick
  • 35,524
  • 46
  • 151
  • 243

3 Answers3

7

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

Andrea Ambu
  • 38,188
  • 14
  • 54
  • 77
2
f = open('inputfile.txt')
for line in f.readlines():
    # the next line is equivalent to:
    # s1, s2 = line.split(' ')
    # a = int(s1)
    # b = int(s2)
    a, b = map(int, line.split(' '))
    print a*b
Nicolas Dumazet
  • 7,147
  • 27
  • 36
  • You cannot make any assumptions about where the newlines are. You might have to add all numbers to a large list (or write a similar generator) and from there pair them off. – Tom Leys Jun 06 '09 at 10:36
  • @Tom: thanks, but I did not quite get you. Would you mind explaining that again? – Nicolas Dumazet Jun 06 '09 at 11:04
0

You could use regular expressions (re-module)

import re

test = "10 11\n12 13" # Get this input from the files or the console

matches = re.findall(r"(\d+)\s*(\d+)", test)
products = [ int(a) * int(b)  for a, b in matches ]

# Process data
print(products)
Dario
  • 48,658
  • 8
  • 97
  • 130
  • 1
    Overkill - Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems. – Tom Leys Jun 06 '09 at 10:37
  • Some people when confronted to a problem think, "I know, I'll quote Jamie Zawinski." Now they've got two problems. http://simonwillison.net/2009/Feb/25/twoproblems/ – Vinko Vrsalovic Jun 06 '09 at 10:53
  • Some people, when facing a problem, think "I'll use regular expressions." Now they have HORDES OF CUTE PEOPLE WANTING TO SLEEP WITH THEM http://twitter.com/yoz/status/1060969730 – Daniel Roseman Jun 06 '09 at 11:14
  • EVERYBODY STAND BACK. I know regular expressions. – Nicolas Dumazet Jun 06 '09 at 11:35