Learn Python Complete Series.
Lecture 6: Outline
- Python Numbers
- Type conversion
- Random numbers
- Practice with example
As we know, mathematical calculations and number conversion is so important part of our life; therefore, Python provides the numeric values to deal numeric datatypes.
Moreover, There are three NumericTypes in _Python_;
Variables, numericTypes are created when you allocate value to them. After the assigning, the variable becomes numericType number.
How to verify?
If you want to check the type of any _Variable_, you can then use the type method or function. Let’s check the example below;
In the first three lines, values are assigned to variables. These are different type of values.
Integer sometime called as int, is a positive or negative whole number with unlimited length without the decimals.
Integers represent positive or negative value. Here below some examples to show the integer numbers.
The above example shows different integers. As we already discuss that integers are positive as well as negative numbers.
click to learn Python complete Series
Float or FloatingPoint Numbers
Float or “floating-point number” is positive as well as a negative number having one or more decimals. In simple, it represents the point value.
Here below some examples below to show the floating-point numbers.
It can also be scientific numbers with an “e” to show the power of TEN(10).
g = 25e2
h = 22E7
i = -87.7e176
print(type(g)) #printing the type of g
print(type(h)) #printing the type h
print(type(i)) #printing the type of i
Complex numbers are written with a letter _”j“_ as the imaginary part:
xx = 3+5j
yy = 4j
zz = -9j
let’s execute the short complex datatype code;
The technique or approach to move on from one data type to another is called typeConversion. You can convert from one type to another by using int(), float(), and complex() functions.
However, Let’s do it with an example to understand better.
Convert from one type to another:
bb = 1 # inttype
yy = 2.8 # floatvalue
zz = 1j # complexvalue
#Now converting values
aa = float(bb)
#convert from float to int:
bb = int(yy)
#convert from int to complex:
cc = complex(zz)
Now you can print one by one to get the converted results. In this way, you can convert any datatype.
NOTE: Keep one thing in mind that you can’t convert complex number to another data type.
For printing a random number from any length, there is no function available in Python. But it has the builtin module or library to print the random number. By using this module, we can print any kind of number from the length.
Import (random) library & print random number from the length of 1-20;
then import random
after that, print(random.randrange(1, 20))
Every time it will give you a random number while executing the code. This example gives you a random number of 4, and next time it will give you maybe another number range. You can try it by own to enjoy the fun of random numbers.
Moreover, visit the official site of Python, here.