0

I'm new to using Python (and dynamically typed languages in general) and I'm having trouble with the my variables being incorrectly-typed at run time. The program I've written accepts 6 variables (all should be integers) and performs a series of calculations using them. However, the interpreter refuses to perform the first multiplication because it believes the variables are type 'str'. Even when I enter integers for all values it breaks at run-time and claims I've entered strings. Shouldn't Python treat anything that walks and quacks like an int as if it were an int?

Thanks in advance.

PS: I'm running Python 3.4.0, if that helps.

  • You might find [this question](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-he-gives-a-valid-response) useful – jonrsharpe Apr 30 '14 at 13:19

2 Answers2

5

input() always returns a string. If you wanted to have an integer, convert your input.

variable = int(variable)

Python doesn't coerce, you need to convert explicitly. Dynamic typing doesn't mean Python will read your mind. :-)

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

You can think of it this way: "Duck Typing" applies to the type of a variable, not of the variable's contents. A string variable is something that can for example be indexed with [] or added to other strings with + and even repeated several times with * {some integer}, but you can't add a string to an integer, even if the string happens to be a number.

The number-ness of a string has nothing to do with the type.

Jasper
  • 3,939
  • 1
  • 18
  • 35