Sunday, 3 April 2016

Numbers in python

Hello, how are you guys!!! I hope you will be fine and also enjoying this tutorial. In my previous post you learned about  python mutable and immutable objects in detail. You also learned the difference between mutable and immutable objects. Today you will learn "Numbers" in python with example.

Numbers in Python:
There are basically two different kinds of numbers in Python. Here in the below screen shot we define a variable. And we will  give it a value (num = 30). And then we will print that variable. You see we get that value.

1. #!/usr/bin/python3
2. def main():
3.    num = 30
4.    print(num)
5. if __name__ == "__main__": main()

Out Put:
30

We can also check the type of number. In the code below in line no 4 we use "type()" function to check the type of a given number.
1. #!/usr/bin/python3
2. def main():
3.    num = 30
4.    print(type(num), num)
5. if __name__ == "__main__": main()

If we run the above code we will get both the type and the value (we see that its class is int, and its value is 30).

Out Put:
<class 'int'> 30

If we declare another variable like num1 and set its value to 30.0, now its type is going to be <class 'float' > 30.0. So those are the two different kinds of numbers in Python. In the below screen shot you see the difference between two.

If I take an integer like "div", and I say div = 30/ 9, I am no longer going to have an integer. If I save this and run it, we will see that I have class 'float' and that it is this real number with a whole lot of digits after the decimal point. If I want to get an integer division, here in the line number 5 I can use two slashes instead of one. And now what I will get, instead of 3.3333333333333335, I will get just 3.

1.#!/usr/bin/python3
2.def main():
3.    div = 30 / 9
4.    print(type(div), div)

5.    div1 = 30 // 9
6.    print(type(div1), div1)

7.if __name__ == "__main__": main()

Out Put:
<class 'float'> 3.3333333333333335
<class 'int'> 3