Forums

Error i don't understand

When I was learning how to use "%s, %d, %r", I thought they are designed to put a string which has been assigned into a new string or a sentence, but when I type like

cars_available=100
print('There are %d cars')%(cars_available)

and it said: TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'

I don't quite understand

[edit by admin: formatting]

The problem is that you've got the brackets in the wrong place.

When you write this:

print('There are %d cars')%(cars _ available)

...Python will break it down into these steps

  • First it will run print('There are %d cars'), which is a function that will return the special value None, which means (like you would expect) "nothing"
  • Then it will run (cars_available), which is just your variable with brackets around it, so it is the number 100.
  • Then it will try to combine the two of them using the % operator; this means it's trying to run code that is the equivalent of None % 100. Because the % operator doesn't know what to do when the first thing it has been provided with is the None object (which has the type NoneType, logically enough) and a number (which is an integer, so it has the type int), it gives that error.

What you want to do, of course, is use the % operator to combine the string 'There are %d cars' with the value in the variable cars_available, and then print the result. You do that by making the brackets surround that part so that Python knows what order to do things in:

print('There are %d cars' % cars_available)