Numbers datatype and Arithmetic operations in Python
We have been dealing with numbers for a very long time, and numbers are essential to any kind of data.
Number data types store numeric values. In Python, Numbers are immutable data types, which means that changing the value of a number data type results in a newly allocated object.
Different types of Number data types are :
- int
- float
Let’s see each one of them:
Int type
int (Integers) are the whole number, including negative numbers with no decimal places. For example, 2 is an integer, but 2.0 isn’t.
let’s see some examples and check the type of numeric data.
num1 = -8 num2 = 8 # print the data type print(type(num1)) print(type(num2)) """ output: <class 'int'> <class 'int'> """
num1 = True num2 = "8" # print the data type print(type(num1)) print(type(num2)) """ output: <class 'bool'> <class 'str'> """
Did you notice something weird?
num2 is a variable with some value that seems integer at first glance, but when we check its type; it returns ‘str’, not ‘int’.
With the above example, we can understand the difference between 8 and “8”. 8 is int while “8” is a string. We will explore the datatype in upcoming blogs.
num3 = "8" # This is not a integer print(type(num3)) # This is string datatype. We will explore the datatype in upcoming blogs """ output: <class 'str'> """
We will witness this problem a lot when we work with numeric data. Are you wondering why it is a problem?
Let’s try to figure it out:
We will add two numbers in the following example (We will see examples of all arithmetic operations later in this blog only. For now, let’s try to add two numbers.
addNumbers = 8 + "8" """ output: print(addNumbers) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-1-176b29b91574> in <module> ----> 1 addNumbers = 8 + "8" 2 3 print(addNumbers) TypeError: unsupported operand type(s) for +: 'int' and 'str' """
You can see the above error. It says, in simple language, that you can’t add a string to a number. it is like adding “apple” and 8, which is impossible.
So we can see such a problem while dealing with numbers. The question, at this point, is how do you tackle this?
addNumbers = 8 + int("8") #We can use int(value) function to convert this type of string to actual value. print(addNumbers) """ output: 16 """
This process of changing datatypes is called typecasting. We have covered it later in the blog.
In Python, there is no limit to how long an integer value can be, which might be surprising considering computers have finite memory.
Try typing the largest number you can think of into IDLE’s interactive window. Python can handle it with no problem!
bigNumber = 9756789017190117119191711910177191011918181 print(bigNumber) print(type(bigNumber)) """ output: 9756789017190117119191711910177191011918181 <class 'int'> """
large_num = 9,000,000 ## Assigning a number 9000000 to variable print(large_num) """ output: (9, 0, 0) """
Weird, right? This is the reason why we avoid commas in Python! 🙂
When you write large numbers by hand, you probably group digits into three groups, separated by a comma. 8,000,000 is a lot easier to read than 8000000.
In Python, you can’t use commas to group digits in integer literals, but you can use an underscore (_). The value 8_000_000 expresses one million in a more readable manner.
a = 8_000_000 print(a) """ output: 8000000 """
Let’s see some arithmetic operations with numbers!
a = 5 b = 6 # Addition c = a + b print("Addition:",c) d = 9 e = 6 # Subtraction f = d - e print("Subtraction:",f) g = 80 h = 3 # Division i = g / h print("Division:",i) # Floor Division i = g // h print("Floor Division:",i) j = 3 k = 5 # Multiplication l = j * k print("Multiplication:",l) m = 25 n = 5 # Modulus o = m % n print("Modulus:",o) p = 6 q = 2 # Exponent r = p ** q print("Exponent:",r) """ output: Addition: 11 Subtraction: 3 Division: 26.666666666666668 Floor Division: 26 Multiplication: 15 Modulus: 0 Exponent: 36 """
Float type
This is a real number with a floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation. . Some examples of numbers represented as floats are 0.5 and -7.823457.
They can be created directly by entering a number with a decimal point or using operations such as division on integers. Extra zeros present at the number’s end are ignored automatically.
num1 = 0.5 num2 = -7.823457 print(type(num1)) print(type(num2)) """ output: <class 'float'> <class 'float'> """
8000000.0000 """ output: 8000000.0 """
8_000_000.0 """ output: 8000000.0 """
To write a float literal in E-notation, type a number followed by the letter e and then another number. Python takes the number to the left of the e and multiplies it by 10, raised to the power of the number after the e. So 8e6 is equivalent to 8×1⁰⁶.
8 * (10 ** 6) """ output: 8000000 """
8e6 # It is 8*10^6 """ output: 8000000.0 """
80000000000000000000.0 """ output: 8e+19 """
The float 80000000000000000000.0 gets displayed as 8e+19. The + sign indicates that the exponent 19 is a positive number.
1e-3 # 1 * 10 ^ -3 # 1 * 1/1000 #-3 represents -10 ^ -3 """ output: 0.001 """
1.2e-3 """ output: 0.0012 """
11.2271617e-3 """ output: 0.0112271617 """
111.2271617e-3 """ output: 0.1112271617 """
1e-5 """ output: 1e-05 """
0.00000000001 """ output: 1e-11 """
0.000001 """ output: 1e-06 """
0.00000001 """ output: 1e-08 """
The literal 1e-3 is interpreted as 10 raised to the power -3, which is 1/1000 or, equivalently, 0.001.
Unlike integers, floats do have a maximum size. The maximum floating-point number depends on your system, but something like 1e500 should be well beyond most machines’ capabilities. 1e500 is 1×10⁵⁰⁰
1e500 """ output: inf """
inf stands for infinity, and it just means that the number you’ve tried to create is beyond the maximum floating-point value allowed on your computer. The type of inf is still float:
type(1e500) """ output: float """
1e500 """ output: inf """
You probably won’t come across inf and -inf often as a programmer unless you regularly work with extremely large numbers.
num = 3/4 # Integer numbers are converted into float as final result # print the value and datatype print(num) print(type(num)) """ output: 0.75 <class 'float'> """
num = 3//4 # print the value and datatype print(num) print(type(num)) """ output: 0 <class 'int'> """
num = 8/4 # Integer numbers are converted into float as final result even if the final value is whole number print(num) print(type(num)) """ output: 2.0 <class 'float'> """
As we have seen, dividing any two integers produces a float.
A float is also produced by running an operation on two floats, or a float and an integer.
num = 6 * 7.0 print(type(num)) """ output: <class 'float'> """
Type Conversion between numbers
We have seen one example of type conversion in the int data type above. Type conversion between numbers is converting datatype of numbers.
We can convert one number into the other form by two methods:
- Explicit Conversion: Explicit conversion is what we did in the above 8 + “8” example. We simply try to convert the values using the same datatype.
for e.g.: to convert “8” into the int, we use int(“8”)
- Implicit Conversion: Using Arithmetic Operations: We can use operations like addition, and subtraction to change the type of number implicitly(automatically), if one of the operands is float.
e.g., 2 is int, but 2/1.0 is a float of the same value. 🙂
Note: This method is not working for complex numbers.
import math a = 8.6 b = int(a) c = math.ceil(a) d = math.floor(a) print(type(a)) print(type(b)) print(a, b, c, d) """ output: <class 'float'> <class 'int'> 8.6 8 9 8 """
Let’s see an example of explicit type conversion!
a = 8 b = float(a) print(type(a)) print(type(b)) print(a, b) """ output: <class 'int'> <class 'float'> 8 8.0 """
Now, let’s see what implicit conversion looks like!
a = 5 b = 6.0 # Addition c = a + b # Any time a float is added to a number, the result is another float. print("Addition:",c) d = 9 e = 6.32 # Subtraction f = d - e print("Subtraction:",f) g = 8 h = 2 # Division i = g / h print("Division:",i) j = 3 k = 5.0 # Multiplication l = j * k print("Multiplication:",l) m = 24 n = 5.0 # Modulus o = m % n print("Modulus:",o) p = 6 q = 2.0 # Exponent r = p ** q print("Exponent:",r) """ output: Addition: 11.0 Subtraction: 2.6799999999999997 Division: 4.0 Multiplication: 15.0 Modulus: 4.0 Exponent: 36.0 """
In the above examples, we are converting the value of one int to float by doing arithmetic operations.
print (2 --5) print (2 - -5) print (2- -5) print (2--5) print (2-(-5)) # Using parentheses is a good idea because it makes the code more explicit. """ output: 7 7 7 7 7 """
In the above example, — and — is +. Hence the results are 7.
Now, let’s see how floor division rounds down the results! Please understand the operation below.
## Integer Division print (27 // 9) print (-5 / 2) print (-5 // 2) # First, -5 is divided by 2 to get -2.5. Then -2.5 is rounded down to -3 print (5 // 2) # On the other hand, 5 // 2 returns 2 """ output: 3 -2.5 -3 2 """
print (1 / 0) # It throws error because you are trying to break a fundamental rule of the universe """ output: --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-53-9b67e3cdef2c> in <module>() ----> 1 print (1 / 0) # It throws error because you are trying to break a fundamental rule of the universe ZeroDivisionError: division by zero """
## Why following expression throws error? print (1 % 0) #This makes sense because 1 % 0 is the remainder of dividing 1 by 0. But you can't divide 1 by 0, so Python raises a ZeroDivisionError. """ output: --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-54-d36f51fd3cb3> in <module>() 1 ## Why following expression throws error? 2 ----> 3 print (1 % 0) #This makes sense because 1 % 0 is the remainder of dividing 1 by 0. But you can't divide 1 by 0, so Python raises a ZeroDivisionError. ZeroDivisionError: integer division or modulo by zero """
print (0 % 1) """ output: 0 """
print (1 / (1 == 0)) """ output: --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-9-cbf7941b7aa7> in <module> ----> 1 print (1 / (1 == 0)) ZeroDivisionError: division by zero """
Zero division error is what we are infinite in maths. In the above example, 1==0 results in False, which again is 0.
print (1 // 0) """ output: --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-5-f3a2f32e0935> in <module> ----> 1 print (1 // 0) ZeroDivisionError: integer division or modulo by zero """
In the blog, we have gone through some general operations with Numbers. These are important to get a basic understanding of how Python works with Numbers, and we will be dealing with numbers a lot, so it becomes extremely important to understand and implement these.