954,557 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to input two integers in Python

I am trying to solve the problem Present at http://www.codechef.com/problems/INTEST/

I have made a small Python script to do my job :-

array = []
no_lines = 0
no = 0 
j=0 
div_no=0
no_lines = input()
no = input()
temp = no_lines 
while(no_lines>0) :
	i=0 
	i = input()
	array[j] = i
	j = j+1
	no_lines = no_lines - 1
j=0

while(j<temp) :
	if array[j] % no == 0 :
		div_no=div_no+1 
	j = j+1

print(div_no,"\n")


I am having a problem in Inputing 2 integers on the same line

no_lines = input()
no = input()


I am really confused...How to get a successful output:-

In case of the following input:-

7 3
1
51
966369
7
9
999996
11


Error:-

SyntaxError: unexpected EOF while parsing
lionaneesh
Junior Poster
109 posts since Feb 2010
Reputation Points: 6
Solved Threads: 5
 

With python 2, don't use input, use raw_input, which returns a string, and convert the result to an int. Here is a modified version which runs (but you didn't choose the fastest way to solve the problem :) )

import sys
if sys.version_info < (3,):
    input = raw_input
    
array = []
no_lines = 0
no = 0 
j=0 
div_no=0
no_lines, no = [int(x) for x in input().split()]
temp = no_lines 
while(no_lines>0) :
	i=0 
	i = int(input())
	array.append(i)
	no_lines = no_lines - 1
j=0

while(j<temp) :
	if array[j] % no == 0 :
		div_no=div_no+1 
	j = j+1

print(div_no,"\n")
Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

Input the two numbers as a string
split the string into a two item list
check if each item is a valid number
then use the index to get at each numeric item
convert each number with float()

Here is a little function to check if a string is numeric ...

def isnumeric(s):
    """test if a string s is numeric"""
    for c in s:
        if c not in "1234567890-+.":
            return False
    return True
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

I did my number checking routine before but simplest is best for me now:

def isnumeric(s):
    try:
       s=float(s)
       return True
    except ValueError: 
       return False

for text in ('one',3242,'342.342','1e6'):
     print text,isnumeric(text)


Or even:

def tofloat(s):
    try:
       s=float(s)
       return s
    except ValueError: 
       return None

def isnumeric(s):
    return tofloat(s) is not None

for text in ('one',3242,'342.342','1e6'):
     print text,tofloat(text)
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: