Python - Integers

An integer (from the Latin integer meaning "whole") is a number that can be written without a fractional component. For example, 21, 4, 0, and −2048 are integers, while 9.75, 5½, and √2 are not. The latter are known as floats.

In Python, integer assignment is as simple as:
(from the shell)

>>> x = 5
>>> y = 6
>>> print(x * y)
30  

Python maintains the types of variables and does not let you mix types when performing operations. This will throw an error:

x = 6  
y = 'This string'  
print(x + y)  
Traceback (most recent call last):  
  File "<stdin>", line 1, in <module>
TypeError:  unsupported operand type(s) for +: 'int' and 'str'  

However, you can get away with this, Python allows it:

x = 2  
y = 'Python is Awesome'  
print(x * y)  
Python is AwesomePython is Awesome  

But this would throw another type error:

x = 2.5  
y = 'Python is Awesome'  
print(x * y)  
Traceback (most recent call last):  
  File "<stdin>", line 1, in <module>
TypeError:  can't multiply sequence by non-int of type 'float'  

Because x is a floating point number.

Craig Derington

Veteran full stack web dev focused on deploying high-performance, responsive, modern web applications using Python, NodeJS, Django, Flask, MongoDB and MySQL.

comments powered by Disqus