0

I am new at Python. Here is my code which scans number of test cases tc as input and then two integers r and c and calculating my result.

Question: How to remove the error?

#!bin/bash/python
tc=int(input());
while tc:
    r,c=raw_input().split()
    if r%2==0:
        r=r/2
    else:
        r=r/2+1
    print(r*c)
    tc=tc-1

4       //input tc
10 10   //input r=10 c=10

Error displayed at the screen:

Traceback (most recent call last):
File "spoj_solders.py", line 5, in <module>
  if r%2==0:
TypeError: not all arguments converted during string formatting

What is this string formatting?

Platform: Ubuntu 10.04

2 Answers 2

2

The line r,c=raw_input().split() takes text from the user (raw_input()), returns it as a str type and splits that into two strings (separated by a space) and stores those in the variables r and c. So, r is a str, you can't say if r%2==0: without casting r to an int like this:

r,c=raw_input().split()
if int(r)%2==0:
    r=int(r)/2
else:
    r=int(r)/2+1
print(r*c)
tc=tc-1
Sign up to request clarification or add additional context in comments.

1 Comment

I want the answer 50 for r=10 & c=10 ,but is giving 1010101010,tc=4
2

The result of the split() call is a list of strings, therefore the r and c variables are also strings.

So, when it comes to using the % operator on r Python is performaning string formatting and not the modulus operation you expect.

You need to cast r into a variable of the correct type first (using float(r) for example).

3 Comments

You should use math.fmod() if you are using a float. If the input is cast to an int instead of a float, using r % 2 is fine. You could always check whether the user has entered a decimal point to determine which method to use.
@jozzas: Try int("1e-5") sometime.
@John if you expect users will provide input in scientific notation, your program should account for that too :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.