Python Numerical types

Numbers are the most important data type for any programmer. There is hardly any serious program we can write without using numbers, so let's discuss some basic numerical types:
  • int (signed integers). Called integers or ints, they are whole numbers (positive, negative, or zero), having no decimal point;
  • float (floating-point numbers). Called floats, they represent real numbers and have a decimal point.
We can start working with a number by just printing it out.

print(13)    # prints 13
print(13.0)  # prints 13.0


Even though 13 and 13.0 are the same number, the former is an integer, and the latter is a float. The simplest way to distinguish them is that floats have a decimal point and integers don't.

We can also use negative numbers as well as zeroes:

print(0)      # prints 0
print(-15)     # prints -15
print(-11.34)  # prints -11.34

Integer numbers is very usefull to count things in the real world while floating-point numbers are a good choice for statistical and scientific calculations.

Printing types

 We also have a way to clearly demonstrate types of different objects using the type() function.

print(type('hello'))  # <class 'str'>
print(type("world"))  # <class 'str'>
 
print(type(100))      # <class 'int'>
print(type(-150))      # <class 'int'>
 
print(type(33.14))     # <class 'float'>
print(type(-0.35))     # <class 'float'>

If you need to know the type of an object, just print it using the type() function.

No comments

Powered by Blogger.