Python supports multiple data types, including a variety of different numeric data types:
Let’s look at some examples.
An integer is a positive or negative whole number without a decimal point. For example:
Above, we see an integer with positive value 1. You can also have negative integers:
Above, we see an integer with negative value 5. We can see that this is an integer by using the type function:
Python tells us this is an integer. We can also calculate with integers. For example:
A float is used to represent real numbers, that is, numbers with a decimal point. For example:
How do we know this is a float? Let’s try the type function again:
This tells us this is a float. We can also calculate with floats:
When you calculate with integers, you might end up with a float:
A complex number is a combination of a real number and an imaginary number. Complex numbers are used in scientific, geometry, or calculus calculations. I never needed these in any of my scripts but for the sake of completeness, I’ll briefly mention them. Here’s an example in Python:
You can also convert between the different numeric types. This can be useful when you have a float and want to get rid of everything after the decimal. Here’s an example of how we can convert a float into an integer:
As you can see above, Python gets rid of everything after the decimal point.
int("5") converts the string “5” into integer 5. Another example:
float("3.2") converts string “3.2” into float 3.2.
You have learned about the different Python numeric data types:
- There are three numeric data types:
- Integer: a positive or negative number without a decimal point.
- Float: a positive or negative number with a decimal point.
- Complex: a combination of a real and an imaginary number and used for advanced calculations.
- We can convert between the three numeric data types.