Python | Numeric data type methods

In the previous post we installed and set up VSCode for Python. From this post onwards we will focus on learning Python language concepts and will write code snippets to understand the concepts.

Optional: Creating chapter-wise Python files

Let's create a directory that will house fresh Python files with code samples from each post in order to keep track of what we've learned so far from each one. For the purpose of keeping all learning in one location, this step is optional but is advised to set up.

  • Open VScode and create new folder python-with-gcptutorials
  • Inside python-with-gcptutorials create file numeric_types.py

vscode-new-file


Create integers, floats and complex numbers

There are three distinct numeric types in Python integers, floating point numbers, and complex numbers. Let's see how to create these data types.

Write code

Write below code snippet in numeric_types.py and save the file.

   
# create an integer
num1 = 123
print(type(num1))

# create a floating point number
num2 = 234.34
print(type(num2))

# create a complex number
num3 = 5+2j
print(type(num3))
 

Run the script

To run the script click on Run -> Run Without Debugging.

run-python-script

Output
   
<class 'int'>
<class 'float'>
<class 'complex'>
 

In the above snippet we created three variables num1, num2 and num3 for storing integer, float and complex number and used type built-in function to print the data type of variable.


Supported operations on numeric data types

All numeric types (except complex) support the following operations.

Python - Sum of two numbers

   
# sum of two numbers
num1 = 120.2
num2 = 130

print(num1+num2)
 

Output

   
250.2
 

Python - Difference of two numbers

   
# difference of two numbers
num1 = 150.2
num2 = 83

print(num1 - num2)
  
 

Output

   
67.19999999999999
 

Python - Quotient of two numbers

   
# quotient of two numbers
num1 = 100
num2 = 21

print(num1 / num2)
  
 

Output

   
4.761904761904762
 

Python - Floored quotient of two numbers

   
# floored quotient of two numbers
num1 = 100
num2 = 21

print(num1 // num2)
  
 

Output

   
4
 

Python - Remainder of two numbers

   
# remainder of num1 / num2
num1 = 100
num2 = 21

print(num1 % num2)
  
 

Output

   
16
 

Python - Absolute value of number

   
# remainder of num1 / num2
num1 = - 100
num2 = 21

print(abs(num1))
print(abs(num2))
 
 

Output

   
100
21
 

Python - Convert number to integer

   
# convert to integer
num1 = 100.01
print(int(num1))
  
 
 

Output

   
100
 

Python - Convert number to floating point

   
# convert to floating point
num1 = 100
print(float(num1))
 
 

Output

   
100.0
 

Python divmod - Get quotient and remainder

   
# quotient and remainder
num1 = 150
num2 = 16

print(divmod(num1, num2))
 
 

Output

   
(9, 6)
 

Python pow - Get x to the power y

   
# pow - x to the power y
num1 = 2
num2 = 3

print(pow(2, 3))
 
 

Output

   
8