Why do I get "TypeError: not all arguments converted during string formatting" trying to check for an even/odd number?

Question:

This code gives an error

print('type a whole number:')
n = input()
if n % 2 == 1:
    print('Odd');
else:
    print('Even');

I’m assuming there’s something special I have to do to variable n in the if statement? I am a beginner to Python.

Asked By: John Calder

||

Answers:

You need to convert n to an integer first, in py 3.x input() returns a string.:

n = int(input())
Answered By: Ashwini Chaudhary

Here is how to fix it:

n = int(input("type a whole number:"))

Since input() returns a string, you need to convert it to an int first, using int().

Answered By: Thanakron Tandavas

Convert the user input n to an integer first.
i.e. Simply Change :

n = input()

To :

n = int(input())

Also, input() can take a string as an argument, which is printed before taking the input.
So, you can change

print('type a whole number:')
n = int(input())

To

n = int(input('type a whole number:'))
Answered By: pradyunsg

Problem

The user’s input is a string, not an integer, regardless of what was typed. It must be converted to integer first, like so:

# not this:
# n = input()
# but this:
n = int(input())

See How can I read inputs as numbers? for details.

Why this error message?

Python allows a string on the left-hand side of %. However, this has a completely different meaning: the string will be treated as a "template" into which other strings can be substituted. The template string should have one or more "placeholders", which start with a %. There are many possible variations, but the simplest examples look like:

>>> '%s' % 1
'1'
>>> '%s and %s' % (1, 2)
'1 and 2'

(Notice that the first syntax does not use a tuple; if there is only one value to substitute and that value is a tuple, it should be wrapped in its own "singleton" tuple first.)

Because the user’s input does not happen to contain any valid placeholder, the attempt to evaluate n % 2 will therefore try to substitute one value into a supposed "template string" that doesn’t have anywhere to put it. Python reports this as a TypeError. Arguably it should be a ValueError instead (since the problem is that the template string doesn’t contain the appropriate number of placeholders), but calling it a TypeError accidentally points at the real cause: n should have been an integer instead.

Answered By: Karl Knechtel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.