In this Python Tutorial we are going to talk about Python Numbers, so Python Numbers are another type of built in data type in python and numbers are often useful in programming, for example if you want to keep the scores in game. Python treats numbers in several different ways, depending on how they’re being used, and there are three main types of numbers in Python: integers, floating-point numbers and complex numbers.
These are some examples of working with numbers in Python:
- Integers: Integers are whole numbers such as 1, 2, 3, -1, -2, -3, etc. you can perform arithmetic operations on integers, such as addition (+), subtraction (-), multiplication (*) and division (/). for example:
1 2 3 4 5 6 7 8 9 10 11 |
# Arithmetic operations with integers x = 5 y = 3 add = x + y # Output: 8 minus = x - y # Output: 2 multi = x * y # Output: 15 div = x / y # Output: 1.6666666666666667 print(add) print(minus) print(multi) print(div) |
Run the code and this will the result.
- Floating point numbers: Floating point numbers are decimal numbers, such as 1.0, 2.5, 3.14159, -0.5, -1.0, etc. you can perform the same arithmetic operations on floating point numbers as you can on integers. However you need to be careful when comparing floating point numbers for equality, as they may not always be exactly equal due to rounding errors. for example:
1 2 3 4 5 6 7 8 9 10 11 |
# Arithmetic operations with floating-point numbers x = 3.14159 y = 2.0 add = x + y # Output: 5.14159 minus = x - y # Output: 1.14159 multi = x * y # Output: 6.28318 div = x / y # Output: 1.570795 print(add) print(minus) print(multi) print(div) |
- Complex numbers: Complex numbers are numbers that have real part and an imaginary part, such as 1+2j, 2-3j, -4+5j, etc. you can perform arithmetic operations on complex numbers, such as addition, subtraction, multiplication and division. for example:
1 2 3 4 5 6 7 |
# Arithmetic operations with complex numbers x = 1+2j y = 3-4j z = x + y # Output: (4-2j) z = x - y # Output: (-2+6j) z = x * y # Output: (11+2j) z = x / y # Output: (-0.2+0.4j) |
In addition to these basic operations, Python provides different built in functions and modules for working with numbers, such as math module for mathematical functions and random module for generating random numbers.
Overall Python provides rich set of features and functionality for working with numbers, making it a powerful tool for numerical computing and scientific programming.