Topics Covered
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.
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.
<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.
All numeric types (except complex) support the following operations.
# sum of two numbers
num1 = 120.2
num2 = 130
print(num1+num2)
250.2
# difference of two numbers
num1 = 150.2
num2 = 83
print(num1 - num2)
67.19999999999999
# quotient of two numbers
num1 = 100
num2 = 21
print(num1 / num2)
4.761904761904762
# floored quotient of two numbers
num1 = 100
num2 = 21
print(num1 // num2)
4
# remainder of num1 / num2
num1 = 100
num2 = 21
print(num1 % num2)
16
# remainder of num1 / num2
num1 = - 100
num2 = 21
print(abs(num1))
print(abs(num2))
100
21
# convert to integer
num1 = 100.01
print(int(num1))
100
# convert to floating point
num1 = 100
print(float(num1))
100.0
# quotient and remainder
num1 = 150
num2 = 16
print(divmod(num1, num2))
(9, 6)
# pow - x to the power y
num1 = 2
num2 = 3
print(pow(2, 3))
8